Laravel Eager Loading with Condition Relationship Example
In this post we will give you information about Laravel Eager Loading with Condition Relationship Example. Hear we will give you detail about Laravel Eager Loading with Condition Relationship ExampleAnd how to use it also give you demo for it if it is necessary.
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…
Hope this code and post will helped you for implement Laravel Eager Loading with Condition Relationship Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs