ORM (Object Relational Mapping) is used to facilitate database CRUD operations. Laravel comes with Eloquent ORM. This tutorial was created to provide part of Laravel Eloquent ORM’s frequently used scam sheet
- 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');
Code language: PHP (php)
- 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
Code language: PHP (php)
Here are some more useful cheat sheet for NULL or NOT NULL in laravel eloquent.
->whereNull('column')
->orWhereNull('column')
->whereNotNull('column')
->orWhereNotNull('column')
Code language: PHP (php)
Cheat sheet to filter by Day, Month, Year, Date options.
->whereDay()
->whereMonth('column', '=', 1)
->whereYear('column', '>', 2019)
->whereDate('column', '>', '2019-05-05')
Code language: PHP (php)
- 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;
Code language: JavaScript (javascript)
Make sure to remove this from the migration
Code language: PHP (php)$table->timestamps()
- restore() soft deleted Eloquent
Use the restore() method to undelete a record.
User::withTrashed()->where("id",1)->restore()
Code language: PHP (php)
Make sure to add following lines in the model to enable SoftDeletes.
use SoftDeletes;
Code language: PHP (php)
- 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();
Code language: PHP (php)
- 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);
Code language: PHP (php)
- 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();
});
Code language: PHP (php)
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();
});