Martin Carlin

Redirecting back to a paginated results page in Laravel

Reading time: Only a minute

in laravel, eloquent, pagination

Apologies if this is obvious, but thought it could possibly help others. I had this link on a product detail page to redirect back to the results page:

<a href="{{ URL::previous() }}">Search Results</a>

but after the page reload triggered by adding the item to the basket, that link would go 'back' to the same page (not to mention the possibility of navigating to the page from somewhere other than the results page). I couldn't think of any way around it but managed to fix it by updating the controller method for the search results page. The items are fetched using the inbuilt paginator:


/* query logic */

$items = $items->paginate(15);

$url = $items->url($items->currentPage()); // e.g. /some-url?page=1

// then append all the get params to the string from above
foreach ($request->all() as $key => $value) {
    $url .= '&' . $key . '=' . $value;
}

$request->session()->put('results-route', $url);

then use <a href="{{ Session::get('results-route') }}">Search Results</a> instead.

Not sure if there's a neater way but chuffed I managed to come up with a solution, had no idea how I was going to fix that.