Laravel Relationship Eager Loading with Condition Example

By Hardik Savani November 5, 2023 Category : Laravel

In this post, we will lean how to write conditional statement with eager loading in laravel. we can write where, wherehas condition with laravel eager loading. i will give you simple example of where condition eager laravel relationship model. you can easily use this post with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10.

Eager Loading is a concept of laravel relationship and it is a best. But we some time taking relation model data at that time we need to add condition like active data or only enabled data etc as per our logic. so we can do it in laravel eager loading.

You can see following example will easily understandable. Let's see bellow example. So might be it can help you.

Simple Condition Example:

$posts = Post::with([

'comments as active_comments' => function (Builder $query) {

$query->where('approved', 1);

}

])->get();

Nested Condition Example:

$posts = Post::with([

'comments.user' => function (Builder $query) {

$query->where('active', 1);

}

])->get();

I hope it can help you...

Tags :
Shares