Load Relationships Always, but Dynamically in Laravel

Hello Artisan in this tutorial i will show you how you can automatically eager load your relationship without calling it in your query. In this laravel eager loading tutorial you will learn how to work with laravel eager load.

To do it i will use laravel model attributes $with. So let's check it. You can not only specify what relationships to ALWAYS load with the model, but you can do it dynamically, in the constructor method: See the below example to understand

App\Models\ProductTag.php

class Product extends Model
{
    protected $with = ['tags'];

    public function __construct() {
       
        $this->with = ['tags'];
    }
}

 

Now you can check it. When you call Product::all() or just like a query with eloquent with Product model, it will automatically load relationship. You can define multiple relationship in with array. Hope it can help you.