Laravel 4 - two pagination in a single page
Alright, if you’re existing Laravel user, you know that Laravel has make pagination easy. If you’re new, I will show you how.
First of all, in your app/routes.php
1 |
|
When user enter http://<your url>.com/items
, it will matched and call the getIndex
method in ItemController
class
app/controllers/ItemController.php
1 |
|
app/models/Item.php
1 |
|
- Get the data from query string
- Look for the
Item
and paginate it to n items per page - Pass in the necessary value to the view
- Create a class named
Item
and extendsEloquent
ORM, it will make your life easy
Do you realise there is no current page for pagination? Laravel did it for you. It will passed in the page=3
for
example into the query string, so the paginate
method will get the value from page
(in this case is 3)
and indicate that it is the current selected page.
The problem now is, what if I want to have 2 pagination in a single page?
Assumption:
- each page has 10 items
Let’s take an example, there are 2 tabs of listing, both under the same page/same URL, let’s called it
impression & conversion. Example, I have 999
items in impression, but I have only 44
items
in conversion, on the impression when I click on page 10, it will shows the 101th item to 110th item,
whereas conversion tab shows nothing. You know why? Because both of them taking the same argument from query
string, i.e. page=10
, both of them also look for page 10. What we want is impression page 10, but conversion
remain page 1.
Solution
One of the solution that I found out is implement by using AJAX.
1. Add in an extra routes
app/routes.php
1 |
|
The where
condition is to only match for either impression
or conversion
. Note that
you must put it above the items
. Always put the more precise route to above.
2. Implement the ajax method in ItemController
app/controllers/ItemController.php
1 |
|
- I’m not return JSON on the AJAX call, but instead, I return the whole bunch of HTML.
But before that, make sure you create a model class for both impression & conversion just like
what you did for Item.php just now.
3. Create a new view file that keep only the particular section of code
app/views/item_type.php
1 | <table class="table"> |
- The pagination link I also included into the ajax, this will make your life easier.
4. Then add in the Ajax call on the main view file
add the section to bottom right before </body>
app/views/items.php
1 | $(function() { |
- Look for the selected page number
- Create an event listener to listen the
onclick
event on the pagination link. - When the page first loaded (which has no any click yet), load the first page of both items.
You have done. See the result