silverstone12's avatar

Using query strings and pagination

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?

0 likes
3 replies
pmall's avatar
pmall
Best Answer
Level 56

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'));
}
1 like
neovive's avatar

@pmall Great solution! Very clean. I was researching some best practices for using query strings in Laravel and could only find various posts on Stack Exchange. I'm surprised @JeffreyWay hasn't covered this in a video. Query strings are great for search options and other parameters that don't need to be part of indexed url's.

Please or to participate in this conversation.