Table of Contents
Laravel Eloquent ORM provides a whole lot of useful functionality that allows you to work with your database tables and relationships using an eloquent expressive syntax.
So, here are some of the features you might often reach out to for ease of use and cleaner code in your Laravel project.
Finding First Record or Records
Here’s an example of finding a post with id.
// Instead of this
$post = Post::find($id);
if(!$post) {
abort(404);
}
// Do this
$post = Post::findOrFail($id);
Or, you can even find multiple records at once by passing an array of IDs as the second argument.
$posts = Post::find([1,2,3]);
Even specify the id with the fields to select as the second argument.
$post = Post::find(1, ['title', 'description']);
$post = Post::findOrFail(1, ['title', 'description']);
Model booted() Method
In this method, you can specify what to do on different model events such as creating, updating, deleting, etc. by passing a closure function.
class User extends Model
{
public static function booted()
{
static::creating(function ($user) {
// delete comments
// delete images
});
static::updating(function ($post) {
// update comments
// update images
});
}
}
Change Default Model Properties
These are only a few of the default properties of an eloquent model you often would reach out. You can change the values according to your needs.
class Post extends Model
{
// The table associated with the model.
protected $table = 'posts';
// fields that can be filled using mass assignment Post::create()
protected $fillables = ['title' , 'description'];
// Eager load relations everytime you fetch posts
protected $with = ['comments'];
// appends accessors to the model's array form.
protected $appends = ['formatted_date', 'short_title'];
// The primary key associated with the table.
protected $primaryKey = 'post_id';
// Indicates if the IDs are auto-incrementing.
public $incrementing = false;
// Indicates if the model should be timestamped.
public $timestamps = false;
// The storage format of the model's date columns.
protected $dateFormat = 'U';
// change the names of the columns used to store the timestamps
const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';
}
Counting Related Models
You can retrieve the number of results from a relationship without actually loading them you may use the withCount
method.
Define a relation comments()
:
public function comments()
{
return $this->hasMany(Comment::class);
}
Then, you can use it like this:
$posts = Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
BelongsTo Default Models
Instead of checking relation data everywhere
{{ $post->author->name ?? '' }}
You can return a default empty model with no relation attached to it.
public function author()
{
return $this->belongsTo(Author::class)->withDefault();
}
You can even set a default value for the default empty model.
public function author()
{
return $this->belongsTo(Author::class)->withDefault([
'name' => 'Someone'
]);
}
getOriginal Method
You can retrieve original values like this after mutating values in your model.
$post = Post::first();
$post->title; // Something title
$post->title = "new title"; // new title
$user->getOriginal('title'); // Something title
This especially comes in handy when you have an accessor same as the name of your column field. For example.
class Post extends Model
{
public function getImageAttribute($value)
{
return asset("storage/$value");
}
//....
$post->image; // will return https://url.com/image-location.jpg
$post->getOriginal('image'); // image-location.jpg
Raw Query Methods
Sometimes, you just need some raw SQL query in your Eloquent builder. Luckily, you can do this with this function.
// whereRaw
$orders = DB::table('orders')
->whereRaw('price > IF(state = "TX", ?, 150)', [300])
->get();
// havingRaw
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();
// orderByRaw
User::where('created_at', '>', '2022-11-15')
->orderByRaw('(updated_at - created_at) desc')
->get();
Create Additional Things When Creating a Model
This artisan command will only create a model.
php artisan make:model Post
There are helpful flags that can generate files related to the model for you.
php artisan make:model Post -fmcr
- -f will create a factory file
- -m will create a migration file
- -c will create a controller file
- -r will create a controller with resourceful functions
Recently and Dirty Method
You can determine if the model was recently created using wasRecentlyCreated
.
$post = Post::create($attributes);
if($post->wasRecentlyCreated) {
// do something
}
Or check if the model attributes have changed or modified using isDirty().
$post = Post::first();
$post->isDirty(); //false
$post->title = "New Title";
$post->isDirty(); //true
Increment and Decrement Methods
Instead of doing this way:
$post = Post::find($id);
$post->views++;
$post->save();
You can do this way:
// you can increase using
$post = Post::find($id);
$post->increment('views');
// or you can decrease using
$post = Post::find($id);
$post->decrement('views');
If you find this useful, check out other of our tutorials and projects. There you might find something to learn and new things you didn’t know about.