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);
}
@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);
@fylzero cheers! So I should use a single endpoint for my search/filters and just differentiate them by the request parameters?
@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.
@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 sign in or create an account to participate in this conversation.