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

normykinz's avatar

Multiple Chained "when" Methods in Eloquent Query

I'm trying to use multiple whens depending on whether a filter has values or not. But it's not working auite as I expected.

If there's no search then it will filter by type (if there is one) but not if there is a search. Anybody fancy helping me out? I'll be your best buddy!

User::query()
            ->when($filter->search, function ($query, $value) {
                $query->where('name', 'like', "%$value%")
                    ->orWhere('email', 'like', "%$value%");
            })
            ->when($filter->type, function ($query, $value) {
                $query->where('type', $value);
            })
			...
0 likes
3 replies

Please or to participate in this conversation.