• Calculating...
  • 5 years ago
  • 10.9K Views
  • Archived This is an Archived post.
    The content within this may not be used or replaced with newer versions.

Laravel Cheat Sheet for Eloquent ORM

ORM (Object-relational mapping) is used to make database CRUD operations easier. Laravel comes with Eloquent ORM. This tutorial is created to provide some of the frequently used cheat sheet for Laravel Eloquent ORM

 

  1. Ordering Eloquent hasMany() relationship

Add ->orderBy() to the hasMany relationship to get ordered output of a specified column.

return $this->hasMany('Detail::class')->orderBy('column');
 
  1. Eloquent’s where() method

Here are some useful cheat sheet for eloquent’s where() method.

$detail = Detail::where("id","!=",50)->get();
// Any of the following may be used as the second parameter (and use the third param for the value)
// =, <, >, <=, >=, <>, !=, LIKE, NOT LIKE, BETWEEN, ILIKE

$detail = Detail::where(function ($query) {
  $query->where('a', '=', 1)
      ->orWhere('b', '=', 1);
})->get();

$detail = Detail::whereRaw('age > ? and votes = 100', array(25))->get();

$detail = Detail::whereRaw(DB::raw("id in (select detail_id from students GROUP BY students.detail_id)"))->get();

$detail = Detail::whereExists(function($query){
  $query->select(DB::raw(1))
      ->from('students')
      ->whereRaw('students.detail_id = details.id')
      ->groupBy('students.detail_id')
      ->havingRaw("COUNT(*) > 0");
})->get();
// Any of the following may be used instead of Detail::whereExists
// ->orWhereExists(), ->whereNotExists(), ->orWhereNotExists()

$detail = Detail::whereIn('column',[1,2,3])->get();
// Any of the following may be used instead of Detail::whereExists
// ->orWhereIn(),

$detail = Detail::whereNotIn('id', function($query){
  $query->select('student_id')
  ->from('students')
  ->groupBy('students.student_id');
})->get();

// Any of the following may be used instead of Detail::whereExists
// ->whereNotIn(), ->orWhereNotIn
 

Here are some more useful cheat sheet for NULL or NOT NULL in laravel eloquent.

->whereNull('column')
->orWhereNull('column')
->whereNotNull('column')
->orWhereNotNull('column')
 

Cheat sheet to filter by Day, Month, Year, Date options.

->whereDay()
->whereMonth('column', '=', 1)
->whereYear('column', '>', 2019)
->whereDate('column', '>', '2019-05-05')
 
  1. Prevent Eloquent from adding created_at or updated_at timestamps

Disable both created_at and updated_at in the model to disable the timestamps

const UPDATED_AT = null;
const CREATED_AT = null;
 

Make sure to remove this from the migration

$table->timestamps()
 
  1. restore() soft deleted Eloquent

Use the restore() method to undelete a record.

User::withTrashed()->where("id",1)->restore()
 

Make sure to add following lines in the model to enable SoftDeletes.

 use SoftDeletes; 
 
  1. Joins in Eloquent

Here are some useful cheat sheet for eloquent’s join() method.

$product = Product:where('id', $productId)
    ->join('businesses','product.business_id','=','businesses.id')
    ->select('product.id','businesses.name')->first();

$product = Product:where('id', $productId)
    ->leftJoin('businesses','product.business_id', '=', 'businesses.id')
    ->select('product.id','businesses.name')->first();

$product = Product:where('id', $productId)
    ->join('businesses',function($join) use($cats) {
      $join->on('product.business_id', '=', 'businesses.id')
    ->on('product.id', '=', $cats, 'and', true);})->first();
 
  1. Find an item by Primary Key in Eloquent, or throw a ModelNotFoundException

findOrFail($id) method will find a model by it’s primary key or throw an exception if it’s not available.

$id = 10001;
$user = User::findOrFail($id);
 
  1. Cache in Eloquent

You can retrieve an item from the cache without loading it all the item.

$details = Cache::remember('details', $seconds, function () {
    return DB::table('details')->get();
});
 

rememberForever method is used to retrieve an item from the cache or store it forever

$details = Cache::rememberForever('details', function () {
    return DB::table('details')->get();
});
 

Hope this tutorial helped you! Feel free to drop your opinion at the comment section.

Share:

Related Post

CRUD Operations In Laravel 8

This tutorial is created to illustrate the basic CRUD (Create , Read, Update, Delete) operation using SQL with Laravel 8. Laravel is one of the fastest-growing frameworks for PHP.

  • 3 years ago

Scheduling Tasks with Cron Job in Laravel 5.8

Cron Job is used to schedule tasks that will be executed every so often. Crontab is a file that contains a list of scripts, By editing the Crontab, You can run the scripts periodically.

  • 5 years ago

Connecting Multiple Databases in Laravel 5.8

This tutorial is created to implement multiple database connections using mysql. Let’s see how to configure multiple database connections in Laravel 5.8.

  • 5 years ago

Integrating Google ReCaptcha in Laravel 5.8

reCAPTCHA is a free service from Google. It’s a CAPTCHA-like system designed to recognize that the user is human and, at the same time, assist in the digitization of books. It helps to protects your w

  • 5 years ago

Clearing Route, View, Config Cache in Laravel 5.8

Sometimes you may face an issue that the changes to the Laravel Project may not update on the web. This occures when the application is served by the cache. In this tutorial, You’ll learn to Clear App

  • 5 years ago