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

anton123's avatar

How to handle an empty search query?

Hi, I'm currently trying to implement a search functionality in my API. Unfortunately, when I leave an empty query the API returns absolutely nothing. Any idea what I'm doing wrong?

Route:

Route::get("/products/search/{title?}", "searchTitle");

Controller function:

public function searchTitle(Request $request, $title = "" )
{
    $pageSize = $request->page_size ?? 10;
    if ($title == "") return Product::query()->paginate($pageSize);
    else return Product::where("title", "LIKE", "%" . $title . "%")->paginate($pageSize);
}
0 likes
4 replies
fylzero's avatar

@anton123 I would recommend not making the search query (specifically the query term) part of the URI. Do it as a querystring/request.

Aside from that, you can use when in your Eloquent query instead of the if/else here.

return Product::query()
    ->when($title, function ($q) {
        return $q->where('title', 'LIKE', "%{$title}%");
    })
    ->paginate($request->page_size ?? 10);
anton123's avatar

@fylzero cheers! So I should use a single endpoint for my search/filters and just differentiate them by the request parameters?

fylzero's avatar

@anton123 I would make /search the endpoint and pass the query and filters via a querystring.

/products/search?q=Search%20query&limit=10&active=true

Once you do that, you can just use when for each filter and query to make the Eloquent string singular / chainable / easier to read.

1 like
anton123's avatar

@fylzero thank you! I did the same thing this morning but set it to the same endpoint. I will split them up later tonight :)

Please or to participate in this conversation.