Ajax-based pagination Laravel 4

Pagination of dataset is a hot topic when it comes to frameworks. I have to agree that Laravel makes pagination a breeze. We almost have to do nothing but chain up a paginate() method with out dataset and we are almost there. Only other thing that we have to do is adding the pagination link method into our view and we are done. Bravo! But hey, what if I want it to be paginated so that it does not refresh the page. Let me be a little more geeky and say we want to ajaxify the pagination.

Now, it might seem like a difficult task at first but it’s not. Al little bit of javascript with some html structural changes and a few PHP conditions will do it! 🙂

Let me show you how.

First of all, make sure you have paginated your resultset using default pagination provided by Laravel. Now since we have out pagination like and it’s working as it should, add the following JavaScript into the
footer of your template or wherever you feel it should be.

What it does it take all the pagination anchor tags and move their HREFs into data attribute and make the HREFs javascript:void(0). Classic, right?

Later in the code we bind clicks on the anchor tags to ajax calls to their respective URLs saved in the data attribute.

Congratulation, we are halfway there folks 🙂

Now, alter your view which loops over the result set in such a way that div/section with the class ajaxable or any other name you have chosen covers starts above the loop and ends after the pagination links.

After that, go over to the controller action and change the layout based on Request::isAjax() method. Change views based on above method and we are done.

Download the sample controller and view.

alexey

alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.
alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.