Home > Back-end >  How to handle an empty search query in Laravel 9?
How to handle an empty search query in Laravel 9?

Time:07-25

I'm currently trying to implement a search functionality in my Laravel 9 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');
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);
    }
}

CodePudding user response:

I suggest you use Conditional Clauses (when), something like this:

return Product::when($title !== '', function (Builder $query, $title) {
    return $query->where('title', 'LIKE', "%$title%");
})
    ->paginate($pageSize);

Or use the object assign to a variable and make the where

 $product = Product::query();

 if ($title !== '') {
     $product->where('title', 'LIKE', "%$title%");
 }
 
 return $product->paginate($pageSize);
  • Related