Donny van V
Donny van V

Reputation: 961

Laravel Eloquent -> get only events where city is

I have a table with:

Events
Cities
Clubs

The relations are as following:

I want to add a filter to my query to get all events where the club.city == 'Oklahoma'. This is what I tried:

$events = Event::where( 'accepted', 1 )
                ->with( [ 'club.city', 'organisation' ] )
                ->where( 'club.city.name', 'Rotterdam' )
                ->orderBy( 'created_at', 'asc' )
                ->paginate( 6 );

Upvotes: 0

Views: 488

Answers (1)

lagbox
lagbox

Reputation: 50491

You can use whereHas to filter based on existance of a condition on a relationship.

$events = Event::where( 'accepted', 1 )
    ->with( [ 'club.city', 'organisation' ] )
    ->whereHas('club.city', function ($q) use ($cityname) {
        $query->where('name', $cityname);
    })->orderBy( 'created_at', 'asc' )
    ->paginate( 6 );

Upvotes: 1

Related Questions