Laravel Eager Loading with Condition Relationship Example

By Hardik Savani | August 18, 2019 | 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 and laravel 8.

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);



Nested Condition Example:

$posts = Post::with([

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

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



I hope it can help you...

Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. 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, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: