a.verrecchia's avatar

Conditional 'When' 'orWhereHas' Statements

Why is it that when I pass through the 'term' filter, the 'year' condition isn't being applied? Specifically, I want the block above to remain fixed, and then the code inside it for the 'when' to be a separate condition applied only if it's present.

$query = Quote::query() ->where('activity_id', $activity->id) ->whereNotNull('number') ->whereYear('date', 2020); // Carbon::now()->year

    $query->when($filters['term'] ?? null, function ($query, $term) {
        return $query->where('number', 'like', '%' . $term . '%')
            ->orWhere(function ($orWhere) use ($term) {
                $orWhere->orWhereHas('user', function($users) use ($term) {
                    $users->whereRaw("CONCAT(firstname, ' ', lastname) LIKE ?", ['%' . $term . '%']);
                })
                    ->orWhereHas('vehicle', function ($vehicles) use ($term) {
                        $vehicles->whereRaw("CONCAT(plate, ' ', brand, ' ', model) LIKE ?", ['%' . $term . '%']);
                    });
            });
    });
0 likes
3 replies
tisuchi's avatar

@a.verrecchia This might work.

$query = Quote::query()
    ->where('activity_id', $activity->id)
    ->whereNotNull('number')
    ->whereYear('date', 2020) // Carbon::now()->year
    ->when($filters['term'] ?? null, function ($query, $term) {
        return $query->where(function ($query) use ($term) {
            $query->where('number', 'like', '%' . $term . '%')
                ->orWhereHas('user', function($users) use ($term) {
                    $users->whereRaw("CONCAT(firstname, ' ', lastname) LIKE ?", ['%' . $term . '%']);
                })
                ->orWhereHas('vehicle', function ($vehicles) use ($term) {
                    $vehicles->whereRaw("CONCAT(plate, ' ', brand, ' ', model) LIKE ?", ['%' . $term . '%']);
                });
        });
    });
a.verrecchia's avatar
a.verrecchia
OP
Best Answer
Level 1

@tisuchi No, I've solved the issue; it was the inner condition that should be 'orWhereRaw.' It was interfering with the year-based results.

$users->orWhereRaw("CONCAT(firstname, ' ', lastname) LIKE ?", ['%' . $term . '%']);
1 like
Snapey's avatar

please learn to format your code blocks

1 like

Please or to participate in this conversation.