Laravel is constantly evolving along with new features. At the writing of this article, its latest version is 9.16.0. In this version, a very common eloquent feature has been added to make it easier to work with eager loadings with conditions. In simple terms, now we can use withWhereHas
method to eager load data with conditions removing the code duplications.
Let us suppose that we have a users
and posts
tables. The users
table stores information about the user details whereas posts
store information about the posts as the name suggests. There is a hasMany relationships between users and posts tables. That is, one user can have many posts.
Old method
In our example, we want to eager load the posts where the status is published. We can achieve this with the following query. But the problem with the following code is that we need to duplicate the query.
<?php
$user = User::query()
->with(['posts' => function($query) {
$query->where('status', 'published');
}])
->whereHas('posts', function($query) {
$query->where('status', 'published');
})
->get();
With withWhereHas Method
To remove the code duplication of the above code, we got a new feature in Laravel 9.16. We can use withWhereHas
method which will do the same query in the background but with fewer lines of code.
<?php
$user = User::query()
->withWhereHas('posts', function($query) {
$query->where('status', 'published');
})
->get();
This will output the same same query result as previous query. A sample output is given below.

This is a very frequently used condition and the new feature will help to write better clean code.