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

Udev's avatar
Level 2

Filter with empty query value

I have a category model which can have sub-categories.

id
category_id
name
...

I have a route to search categories

GET /categories/search?category_id=

I want to return:

i) Only categories without parents if category_id is empty but is in the query

ii) All categories if the category_id is not in the query

iii) Categories with category_id as a parent if category_id is in the query and has a value

I have tried

Category::when($request->category_id, function ($query, $category_id) {
                    $query->where('category_id', $category_id);
                })->get()
0 likes
1 reply
Udev's avatar
Udev
OP
Best Answer
Level 2

managed to solve this

Category::when($request->has('category_id'), function ($query) use($request) {
                    $query->where('category_id', $request->category_id);
                })->get()

Please or to participate in this conversation.