if your search will become more complex, take a look at this package:
https://github.com/nicolaslopezj/searchable
Might help you and makes things easier
I'm trying to create a page that displays products from my database. It contains a search bar at the top, and then just lists products underneath. Here is the code from my controller:
public function index(Request $request)
{
$query = $request->input('search');
if ($query) {
$comics = Comic::where('name', 'LIKE', "%$query%")->paginate(8);
$comics->setPath('');
} else {
$comics = Comic::paginate(8);
$comics->setPath('');
}
return view('comics.index', compact('comics', 'query'));
}
This works but it feels really messy - if the user has not made a search, it will get all the comics from the database and paginate them. Otherwise, if there is a search, it will only get those results and then paginate them. I don't understand the $comics->setPath(''); thing either, but it doesn't work without it.
I'd like to add more search options, such as tags or genres, but I think if continue with what I have it will become even more of a mess. Anyone know how I can improve this?
Create a scope for searching. In Comic model :
public function searchScope ($query, $q)
{
// Nothing if no q
return if (! $q);
// Search the q
$query->where('name', 'LIKE', "%$q%");
}
It cleans up your controller :
public function index(Request $request)
{
$q = $request->input('search');
$comics = Comic::search($q)->paginate(8);
return view('comics.index', compact('comics', 'query'));
}
Please or to participate in this conversation.