ItSolutionStuff.com

Laravel Relationship Eager Loading with Condition Example

By Hardik Savani • April 16, 2024
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, 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

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Pass an Optional Column to latest() in Laravel Eloquent?

Read Now →

Laravel 10 One to Many Eloquent Relationship Tutorial

Read Now →

How to Use Limit and Offset in Laravel Eloquent?

Read Now →

How to Find Multiple Ids using Laravel Eloquent?

Read Now →

Laravel Eloquent doesntHave() Condition Example

Read Now →

Delete All Records from Table in Laravel Eloquent

Read Now →

Laravel Eloquent inRandomOrder() Method Example

Read Now →

Laravel Relationship Eager Loading with Count Example

Read Now →

Laravel Relationship Eager Loading Example

Read Now →

Laravel Relationship Where Condition Example

Read Now →

Laravel Eloquent Relationships Tutorial From Scratch

Read Now →

Laravel One to One Eloquent Relationship Tutorial

Read Now →

Laravel One to Many Eloquent Relationship Tutorial

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →