10 Laravel 7 Eloquent Tricks

sanz

Sanz

Posted on July 18, 2020

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) {
   abort(404);
}

// Do this
$post = Post::findOrFail($id);
Enter fullscreen mode Exit fullscreen mode

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

$posts = Post::find([1,2,3]);
Enter fullscreen mode Exit fullscreen mode

Even specify id with the fields to select as the second argument.

$post = Post::find(1, ['title', 'description']);
$post = Post::findOrFail(1, ['title', 'description']);
Enter fullscreen mode Exit fullscreen mode

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
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

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';
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

Then, you can use like this:

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

foreach ($posts as $post) {
    echo $post->comments_count;
}
Enter fullscreen mode Exit fullscreen mode

If you find this useful, you can continue on https://laravelproject.com/10-laravel-7-eloquent-tricks/

💖 💪 🙅 🚩
sanz
Sanz

Posted on July 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related