working with Laravel pagination links
Laravel provides a dead simple way to create a pagination links.
It will automatically generate and render the pagination UI with just below code:
However, consider a search scenario where the results based on query search is returned in pagination view.
We will need to a way to maintain/remember the query string when the user is going from one page to the next but how do we add the querying string to the pagination links that's auto generated by Laravel?
You can accomplish this by using the
Here's an example:
Also, consider a scenario where you are on page 5 of the pagination and you click on one of the records to update the record but after the record is updated, you want to come back to the page where you left off... You would need to pass the
Well, I found out that Redirecting to route does not work with query string for some reason so I had to use
Hope this helps!
It will automatically generate and render the pagination UI with just below code:
// inside the controller
$blogs = Blog::sortBy('published_date', 'desc')->paginate(20);
// inside the view
$blogs->links();
// for customized pagination view
$blogs->links('pagination.viewname');
However, consider a search scenario where the results based on query search is returned in pagination view.
We will need to a way to maintain/remember the query string when the user is going from one page to the next but how do we add the querying string to the pagination links that's auto generated by Laravel?
You can accomplish this by using the
appends
method on the eloquent collection.Here's an example:
// inside controller
$blogs = Blogs::where('title', 'like', '%'.$query.'%')->paginate(10);
// inside blade view
{{$blogs->appends(Request::except('page'))->links()}}
Also, consider a scenario where you are on page 5 of the pagination and you click on one of the records to update the record but after the record is updated, you want to come back to the page where you left off... You would need to pass the
$page
variable from view to the controller then back to the redirecting view...Well, I found out that Redirecting to route does not work with query string for some reason so I had to use
Redirect::to()
rather than Redirect::route()
method.
// inside controller
// this doesn't work
return Redirect::route('discussion-topics')->with('page', $page);
// this does work
return Redirect::to(route('discussion-topics').'?page='.$page);
Hope this helps!
Leave a comment
If you sign up and log in:
OK, Sign me up!
However, there are times when unintended content is converted to emoticon because the content happens to have one of the emoticon symbols. That's why it's always good idea to preview your comment before posting and when you see this type of problem, you can indicate NOT to auto convert.