Laravel Eloquent Cheat Sheet |Eloquent ORM

Laravel Eloquent Cheat Sheet |Eloquent ORM

Laravel Eloquent ORM Cheat Sheet. This tutorial provide you all the laravel eloquent ORM.


  ->select(DB::raw('businesses.*, COUNT( as no_of_ratings, IFNULL(sum(reviews.score),0) as rating'))  
  ->distinct() // distinct select


  ->from(DB::raw('table, (select @n :=0) dummy'))
  ->from(DB::raw("({$subQuery->toSql()}) T ")->mergeBindings($subQuery->getQuery())


  ->where(function ($query) {
    $query->where('a', '=', 1)
        ->orWhere('b', '=', 1);
  ->orWhere('column','!=', 'value')
  ->whereRaw('age > ? and votes = 100', array(25))

  ->whereRaw(DB::raw("id in (select city_id from addresses GROUP BY addresses.city_id)"))

        ->whereRaw('business_language.language_id =')
        ->havingRaw("COUNT(*) > 0");

  ->whereNotIn('id', function($query){

  ->whereNull('column') //where `column` is null
  ->orWhereNull('column') //or where `column` is null
  ->whereNotNull('column')  //where `column` is not null 
  ->orWhereNotNull('column')  //or where `column` is not null 

  ->whereMonth('column', '=', 1) //
  ->whereYear('column', '>', 2000) //uses sql YEAR() function on 'column'
  ->whereDate('column', '>', '2000-01-01')


  ->leftJoin('reviews','reviews.business_id', '=', '')
  ->join('business_category',function($join) use($cats) {
    $join->on('business_category.business_id', '=', '')
    ->on('', '=', $cats, 'and', true);
  ->join(DB::raw('(SELECT *, ROUND(AVG(rating),2) avg FROM reviews WHERE rating!=0 GROUP BY item_id ) T' ), function($join){
    $join->on('genre_relation.movie_id', '=', '')

Eager Loading

  ->with(array('posts' => function($query) use($name){
    $query->where('title', 'like', '%'.$name.'%')
      ->orderBy('created_at', 'desc');


  ->havingRaw('count > 1 ')
  ->orHavingRaw('brand LIKE ?',array("%$keyword%"))



Offset & Limit

  ->forPage($pageNo, $perPage)


  ->orderByRaw('type = ? , type = ? ', array('published','draft'))
  ->latest() // on 'created_at' column
  ->oldest() // on 'created_at' column


  ->insert(array('email' => '[email protected]', 'votes' => 0))
    array('email' => '[email protected]', 'votes' => 0),
    array('email' => '[email protected]', 'votes' => 0)
  )) //batch insert
  ->insertGetId(array('email' => '[email protected]', 'votes' => 0)) //insert and return id


  ->update(array('email' => '[email protected]'))
  ->update(array('column' => DB::raw('NULL')))
  ->touch() //update timestamp


  ->forceDelete() // when softdeletes enabled
  ->destroy($ids) // delete by array of primary keys
  ->roles()->detach() //delete from pivot table: associated by 'belongsToMany'


  ->find($id, array('col1','col2'))
  ->findMany($ids, $columns)
  ->getFresh() // no caching
  ->getCached() // get cached result
  ->chunk(1000, function($rows){

  ->lists('column') // numeric index
  ->lists('column','id') // 'id' column as index
  ->lists('column')->implode('column', ',') // comma separated values of a column
  ->pluck('column')  //Pluck a single column's value from the first result of a query.
  ->value('column')  //Get a single column's value from the first result of a query.

Paginated results

  ->paginate(10, array('col1','col2'))
  ->getPaginationCount() //get total no of records


  ->count(DB::raw('distinct column'))
  ->aggregate('sum', array('rating')) // use of aggregate functions


  ->toSql() // output sql query
  ->exists() // check if any row exists
  ->fresh() // Return a fresh data for current model from database

Object methods

  ->toArray() //
  ->relationsToArray() //Get the model's relationships in array form.
  ->implode('column', ',') // comma separated values of a column
  ->getDirty() //Get the attributes that have been changed but not saved to DB


Model::where()->toSql() // output sql query

Recommended laravel tutorial

  1. Laravel Tutorial From Scratch | Step By Step
  2. Laravel 6 Ajax CRUD(DataTables Js) Tutorial Example
  3. Laravel 6 – Ajax CRUD (Operation) Application Example
  4. Laravel 6 Angular JS CRUD Example Tutorial
  5. Upload Files/Images to Amazon s3 Cloud Using Laravel 6 Filesystem
  6. Laravel 6 CKEditor with Image Upload
  7. Ajax Image Upload In Laravel Tutorial Example From Scratch
  8. Laravel 6 Intervention Upload Image Using Ajax – Example
  9. Laravel Upload Image to Database with Validation
  10. Send Email Example Laravel
  11. Generate OR Create PDF In Laravel 6 Example
  12. Laravel 6 Highcharts Example Tutorial
  13. Simple Generator or Create Qr Code Example Laravel
  14. Laravel Custom Cron Schedule Example Tutorial
  15. Laravel 6 Github Login Example

Leave a Reply

Your email address will not be published. Required fields are marked *