working with Laravel pagination links

 David

Laravel provides a dead simple way to create a pagination links.
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!
Go Back to List Page

Leave a comment

Name : Comment : view emoticons
Please consider signing up for our website.
If you sign up and log in:
  •   You can avoid the "I'm not a robot" captcha when commenting
  •   You can also avoid typing your name every time
  •   You can upload a picture for each comment
  •   You can change or delete your comment within 1 hour
  •   You can track all the comments you posted on this site
  •   You can read blog posts that are only open to members
  •   You can look up blogs using the search feature
  •   More privileges for our friends & families coming...

OK, Sign me up!

Emoticons are a great way to visually express how you feel.
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.