How to make an infinite scroll in Laravel and jQuery

If you’d asked yourself how the heck make a really good pagination more dynamically in your webpages, I mean, no need to reload page like twitter or facebook does.

First at all you need to stay here reading this article because I’ll try to explain basics in order to do a complex infinite scroll later, just using Laravel as backend-side service and jQuery as frontend-side client, since these two tools has a very great power, specially jQuery to make pages more dynamically, turning on more versatile the UX as known as user experience, after all I’m not a very geek as to make me blow out my head redesigning the wheel, instead of that I should take advantage of tools there are around of the Internet, obviously giving its respective acknowledgment.

I assume you have a very basics in the PHP Framework of Laravel and naturally Javascript/HTML, thus, it should be mentioned you must understand how the command line of the OS works.

Once you got a fresh installation of Laravel with jQuery’s library loaded correctly in some of your view files, go get an special library that you need for this example which I’m going to leave it in this link, this one will be the one that gonna make the magic, you just simply click on save link as… and proceed to save the file inside in the public folder of the framework. Let’s make a new view file named as pagination.blade.php inside its respective folder located at resources/views and put the following content within the body tag:

<div class="container">  
    @if( isset($viewdata['posts']) && count($viewdata['posts']) > 0 )
    <div id="posts">
        @foreach($viewdata['posts'] as $item)
        <div class="item">
               <h2>{{ $item->title }}</h2>
               {{ $item->description }}
    <span style="visibility: hidden;">
        {!! $viewdata['posts']->render() !!}
    <div class="loading"></div>
    <p>No records founds.</p>

Now in the same file you’ve open, you must prompt at the end of it, before the closing body tag and write the below content within a script block like this:

<script src="/assets/plugins/jquery/jquery-2.1.3.min.js"></script><script src="/assets/plugins/infinite-scroll/jquery.infinitescroll.min.js"></script>  
        navSelector  : "ul.pagination",
        nextSelector : "ul.pagination li:last-child a",
        itemSelector : "#posts div.item",
        loading: {
            finished: undefined,
            finishedMsg: "No more records found to show.",
            img: "/assets/images/reload.GIF",
            msg: null,
            msgText: "Loading...",
            selector: ".loading",
            speed: 'fast',
            start: undefined

As I said, of course you have to load jQuery first of infinite scroll library in order to work like a charm. In the piece of code where I show you the div of posts, you’re gonna see some needed parameters, one of them is navSelector, nextSelector and itemSelector, these are useful to find into the DOM (Document Object Model) the links of the pagination that laravel makes for us, by default it creates an unordered list with a class pagination, so in the parameter nextSelector, you must point to the link inside of the last li tag that exists in the above list.

Another parameters like loading are optionals, I mean, they are not essentials for the correct behavior of the script, but it would looks more fancy, enhancing its UI and UX for the user.

But now you need to write some code in the main function that will bring us the records of a database before loading into the view file, for that, let’s make a new controller that its name would be as PaginationController.php which you can create it with the easier way that laravel provides you and of course it is something that I love of this framework, regardless whether you are on Windows, macOS or linux, you should jump to the command line of the system, prompt to the folder of the project and write down the following command:

php artisan make:controller PaginationController  

This line will make the controller and it is saved directly into the Http folder of the project automatically. Opening the file recently created with your favorite code editor, you’ll face with a function you need (or if isn’t created, you must do it), which it is the index():

public function index() {  
    $posts= Posts::where('enabled', '=', '1')->orderBy('id', 'desc')->paginate(20);
    $this->viewData['posts'] = $posts;
    return view('pagination')->with('viewdata', $this->viewData);

You must first to understand some stuff that if you’ll see in a first instance, you won’t get it, but analyzing, it is not difficult to understand after all. First one of them does a reference to the static class Posts which it is a definition of a Model since Laravel manages the database through an ORM (Object Relationship Mapper), in before you need to go back to our dear friend artisan, creating a new Model with:

php artisan make:model Posts  

But what the heck “this ORM” is? it means is an interface that communicate to your database and convert those SQL queries/resultsets into objects and methods, so, the above code says to you, it calls a method as where, orderBy and paginate respectively of the static class Posts with no need to instantiate an object.
Once the query is done, it’ll create an object that you must pass to the view file through a variable that you need to define as a private one.

And that’s all! So you’re done and you got a very basic page that finds for new records without reload the page like “endless-way”.
You can have a look at the full code from my github profile or just directly to the repository here

If you have some question or comment you want to ask for me, you could follow me at my twitter from @ferdroid8080, and if it is useful you can share the post for supporting.

Leave a Reply