Laravel Relationship Eager Loading with Condition Example
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, laravel 10 and laravel 11.
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Pass an Optional Column to latest() in Laravel Eloquent?
- Laravel 10 One to Many Eloquent Relationship Tutorial
- How to Use Limit and Offset in Laravel Eloquent?
- How to Find Multiple Ids using Laravel Eloquent?
- Laravel Eloquent doesntHave() Condition Example
- Delete All Records from Table in Laravel Eloquent
- Laravel Eloquent inRandomOrder() Method Example
- Laravel Relationship Eager Loading with Count Example
- Laravel Relationship Eager Loading Example
- Laravel Relationship Where Condition Example
- Laravel Eloquent Relationships Tutorial From Scratch
- Laravel One to One Eloquent Relationship Tutorial
- Laravel One to Many Eloquent Relationship Tutorial
- Laravel Many to Many Eloquent Relationship Tutorial