Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

elliotk's avatar

Query Scope for Relationship

Hello,

I have a query which isn't working as I want it to.

Product::with(['categories' => function ($categories) {
                        $categories->enabled();
                    }])
                    ->with('media')
                    ->get();

If we have a Product with no Categories which are enabled(), I don't want the Product returned. So basically, only give me Product where it has at least 1 enabled Category.

I read some old posts about whereHas but I can't find it in the Laravel Docs, has it been dropped?

Any ideas how to solve this one?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You need whereHas to constraint by the relationship:

Product::whereHas('categories', function ($categories) {
	$categories->enabled();
})->with(['categories' => function ($categories) {
	$categories->enabled();
}])->with('media')->get();

Notice that the same constraint is being used for the eager-loaded categories as is used for the constraint; you can assign that Closure to a variable:

$constraint = function ($categories) {
	$categories->enabled();
};
Product::whereHas('categories', $constraint)->with(['categories' => $constraint])->with('media')->get();
elliotk's avatar

Got it. I tried with on its on and whereHas on it's own, but not together.

Seeing it now together it makes sense.

Thanks

Please or to participate in this conversation.