Skip to content

Laravel Eloquent withWhereHas() method

Last updated on November 21, 2022

You filtered data with whereHas() and selected the same records via with(). You no longer need to call both methods. Since Laravel 9.16 you can use withWhereHas() and achieve the same results, instead of calling two methods.

Example:

CollectionModel::whereHas('products', function ($query) {
    $query->where('enabled', true)->where('sale', true);
})->with(['products' => function ($query) {
    $query->where('enabled', true)->where('sale', true);
});

Using the withWhereHas method, you can simplify your code around this use case:

CollectionModel::withWhereHas('products', fn ($query) => $query->where('enabled', true)->where('sale', true));
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments