Full Stack LAMP - MEAN Developer, Python developer. Certified Azure Developer. Freelance programmer/consultant/trainer.

Laravel Eloquent withWhereHas() method

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.


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

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments