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

EricZwart's avatar

Filter query relation

Hi, I have venue's with events. The events have a category. I want to show a page with all venues with their events. But I only want to show the veneus with the category with id '2'. Code below shows the venues containing an event with category '2'.

How can I show only the events that are category '2' because now I see all events.

$venues = Venue::whereHas('event', function (Builder $query) {
            $query->where('category_id', '2');
})->get();

Thanks!

0 likes
4 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You filter with() as well

$venues = Venue::whereHas('event', function (Builder $query) {
            $query->where('category_id', '2');
})->with(['event' => function ($query) {
            $query->where('category_id', '2');
}])->get();
EricZwart's avatar

@Sinnbeck this returns this error:

TypeError
App\Http\Controllers\Admin\VenueController::App\Http\Controllers\Admin\{closure}(): Argument #1 ($query) must be of type Illuminate\Database\Eloquent\Builder, Illuminate\Database\Eloquent\Relations\HasMany given, called in /Users/eric/Code/runevent/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 666

EricZwart's avatar

@Sinnbeck Thats the one. Is that because you already called Builder the first time?

Thanks!!!!!

Please or to participate in this conversation.