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

javitrujillo's avatar

I want to do a when case in an2 Eloquent query.

Hi everyone. I have used the when() for checking if some variables exists, but I want to know if I can use the when() to check if a property of a column of the relation is one thing or another. Something like that:

$dogshows = Dogshow::with('country')->with('club.breeds')->with('thumb')->with('card')
        ->with('shows')
        ->where('active', 1)
        ->whereHas('club', function($q) {
            $q->when('club_type == sb', function($query) {
                $query->whereHas('breeds', function($que) {
                    $que->whereIn('breeds.id', auth()->user()->breed_favorites->pluck('favable_id')->toArray());
                });
            })
            ->when('club_type == ab', function($query) {
                $query->whereHas('system.breeds.breeds', function ($query) {
                    $query->whereIn('breeds.id', auth()->user()->breed_favorites->pluck('favable_id')->toArray());
                });
            });
        })->get();
0 likes
2 replies
tykus's avatar

@javitrujillo that is not the purpose of the Builder's when method; it only evaluates some PHP expression to determine if the Builder should be further modified (as defined in the Closure). If you need to evaluate the condition within the SQL query, then a raw expression would be the approach.

EDIT oops reply was supposed to be general rather than to you @vincent15000

Please or to participate in this conversation.