Skip to content

Instantly share code, notes, and snippets.

@hassansin
Last active April 10, 2025 08:32
Show Gist options
  • Save hassansin/2fb9d72b51860d454316 to your computer and use it in GitHub Desktop.
Save hassansin/2fb9d72b51860d454316 to your computer and use it in GitHub Desktop.
Laravel 5 Eloquent CheatSheet #laravel #eloquent
Model::
/*Select*/
->select('col1','col2')
->select(DB::raw('businesses.*, COUNT(reviews.id) as no_of_ratings, IFNULL(sum(reviews.score),0) as rating'))
/*Query*/
->where('column','value')
->where('column','LIKE','%'.$value.'%')
->orWhere('column','!=', 'value')
->whereIn('column',[1,2,3])
->whereRaw('age > ? and votes = 100', array(25))
->whereNotIn('id', function($query){
$query->select('city_id')
->from('addresses')
->groupBy('addresses.city_id');
})
->whereRaw(DB::raw("id in (select city_id from addresses GROUP BY addresses.city_id)"))
/*Joins*/
->join('business_category',function($join) use($cats) {
$join->on('business_category.business_id', '=', 'businesses.id');
})
->leftJoin('reviews',function($join) {
$join = $join->on('reviews.business_id', '=', 'businesses.id');
})
/*Eager Loading */
->with('table1','table2')
->with(array('table1','table2','table1.nestedtable3'))
->with(array('posts' => function($query) use($name){
$query->where('title', 'like', '%'.$name.'%')
->orderBy('created_at', 'desc');
}))
/*Grouping*/
->groupBy('state_id','locality')
->havingRaw('count > 1 ')
/*Cache*/
->remember($minutes)
->rememberForever()
/*Offset & Limit & Order*/
->take(10)
->limit(10)
->skip(10)
->orderBy('id','DESC')
/*Getters*/
->find($id)
->findOrFail($id)
->first()
->firstOrFail()
->all()
->get()
->lists()
->paginate()
->count()
->count(DB::raw('distinct businesses.id'));
@vgutnar
Copy link

vgutnar commented Oct 18, 2016

Very helpful, thanks!!

@89gsc
Copy link

89gsc commented Nov 17, 2016

Thanks! Bookmarked!

@MisterDuval
Copy link

Thanks, but that one is more complete: http://cheats.jesse-obrien.ca/

@NassimRehali15
Copy link

orWhereNotNull doesn't existe in laravel 5.5 !!

@Sopheak0
Copy link

Sopheak0 commented May 5, 2019

@MisterDuval your link is not valid, can you post a new one?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment