What Is Constraining Eager Loads In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.So today we are going to discuss about Constraining Eager Loading In Laravel with example.

What Is Constraining Eager Loads In Laravel With Example

Eager Loading In Laravel

When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem. To illustrate the N + 1 query problem, consider a Video model that is related to Comments

To know about Eager Loading In Laravel please visit our Bajarangisoft  site.

Lets start.
Constraining Eager Loads In Laravel 

Sometimes you may wish to eager load a relationship, but also specify additional query conditions for the eager loading query. Here's an example:

public function index()
{
    $users = App\User::with(['Video' => function ($query) {
        $query->where('title', 'like', '%first%');
    }])->get();
}
 

In this example, Eloquent will only eager load posts where the post's title column contains the word first. You may call other query builder methods to further customize the eager loading operation:

public function index()
{
    $users = App\User::with(['Video' => function ($query) {
        $query->orderBy('created_at', 'desc');
    }])->get();
}

The limit and take query builder methods may not be used when constraining eager loads.

Related Post