DEV Community


Posted on • Updated on • Originally published at

10 Laravel 7 Eloquent Tricks

Laravel Eloquent ORM provides a whole lot of useful functionality which allows you to work with your database tables and relationships using an eloquent expressive syntax.

So, In here are some of the features which you might often reach out 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) {

// Do this
$post = Post::findOrFail($id);

Or, you can even find multiple records at once by passing array of ids as second argument.

$posts = Post::find([1,2,3]);

Even specify 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 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 like this:

$posts = Post::withCount('comments')->get();

foreach ($posts as $post) {
    echo $post->comments_count;

If you find this useful, you can continue on

Top comments (0)