0
votes

I've followed the instructions on the Laravel documentation for pagination with appends([]) however I'm having a little trouble with the persistence of these parameters.

Say for example, I pass home?category=Cars&make=Tesla to my view. What is the best way to paginate with them Get requests?

Right now I've passed the category as a parameter to the view as (where category is the model i've grabbed findOrFail with the request('category');)

$category_name = $category_model->name;

And then in my view it's like so:

{{ $vehicles->appends(['category' => $category_name])->links() }}

But when I go between pages in the pagination, this $category_name value doesn't seem to persist. Whats the recommended way to achieve what I want?

Thanks.

1

1 Answers

4
votes

You can append the query string in your controller when you paginate the result. I'm not sure if that was your only question or even regarding applying the query string as a condition. So here is a sample showing you how to do both. This should give you an idea of how to do it. I just assumed the column names in this example.

$category = request('category');
$make = request('make');

$vehicles = Vehicle::when($category, function ($query) use ($category) {
        return $query->where('category', $category);
    })
    ->when($make, function ($query) use ($make) {
        return $query->where('make', $make);
    })
    ->paginate(10);

$vehicles->appends(request()->query());

return view('someview', compact('vehicles'));