Laravel Eager Loading with Condition Relationship Example

Laravel Eager Loading with Condition Relationship Example


tutorials -

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.

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...

Trending On Tutorial Stuff

Our Sponsors

Top Applications in Tutorial Stuff

Top Experts In Tutorial Stuff