Using Laravel's Pagination to create infinite scroll
Udgivet 2018-04-28 - Skrevet af Philip Sørensen
Infinite scroll is awesome. I use it here in my article feed, where you'll start by seeing the latest few articles, and if you keep scrolling more articles appear. You can see it here: Article feed
But how do you implement it? In Laravel you do it with pagination.
What is pagination?
Pagination refers to dividing a single document into several discrete pages. With regards to my article feed, this means that instead of showing all my articles at once, they are divided into smaller clumps that are loaded as needed.
This is rather clever, because instead of loading everything at once, the website can “lazy load” articles as needed. Furthermore, the feed becomes more manageable for the user.
How to use pagination in Laravel
The implementation of pagination is Laravel is actually pretty simple, because it is integrated into the query builder and the Eloquent ORM. All you have to do is call the paginate function, like shown below.
In this example I state that I want to show 5 articles “per page”. This means that 5 articles will be displayed at the beginning, and another 5 will be loaded each time it is triggered.
That is all it takes to implement infinite scroll in the controller. Now let's take a look at the view.
Before implementing the lazy loading, I had the following code in the view to display articles:
To get the pagination to work with that, you need to wrap it into a
, like shown here:
Another important thing to note here is the
. This shows page number links. I will, however, hide them with jQuery and use an auto trigger to simply append the pages. The jQuery script to do that can be seen here:
The script hides the page links that Laravel renders with the links-method, and it enables JScroll on the infinite scroll div. However, to get this script running, what you have to do is to add jQuery (version 1.8.0 or newer) and JScroll. This can be achieved with the following HTML:
And now you're set.
Quite simple, wasn't it?
To sum up, all you had to do was:
- Fetch your articles with paginate instead.
- Wrap your foreach-loop in a div.
- Add jQuery and JScroll.
- Add a jQuery script.
A live preview of this can be seen here: Article feed
. The example I have used throughout the code here was an article feed, however you could implement any type of list with infinite scroll. This could for example be an album, a list of employees, etc. It is really versatile.
I hope you enjoyed this guide, see you in the next one!
Der er ingen kommentarer.