Implementing Infinite Scroll with Laravel and jQuery
Rafa Rafael

Rafa Rafael @rafaelogic

About: Dad / Husband / Full Stack Developer / Lifelong Learner

Location:
Northern Mindanao, Philippines
Joined:
Oct 12, 2023

Implementing Infinite Scroll with Laravel and jQuery

Publish Date: Aug 22 '24
4 2

Infinite scroll provides a more modern and fluid way of loading data compared to traditional pagination. Instead of clicking on pagination links, new data is automatically loaded as the user scrolls down the page.

Prerequisites

  • Basic knowledge of Laravel and jQuery.
  • A Laravel project with a model to paginate (e.g., User).

Step 1: Setting Up Laravel for Pagination

First, set up your controller to handle pagination:

// In your UserController
public function index(Request $request)
{
    $users = User::paginate(10); // Paginate the results, 10 per page

    if ($request->ajax()) {
        return view('users.partials.users_list', compact('users'))->render();
    }

    return view('users.index', compact('users'));
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the View

Create views to display the paginated data:

resources/views/users/index.blade.php

@extends('layouts.app')

@section('content')
<div id="user-list">
    @include('users.partials.users_list', ['users' => $users])
</div>
<div id="loading" style="text-align:center; display:none;">
    <p>Loading more users...</p>
</div>
@endsection
Enter fullscreen mode Exit fullscreen mode

resources/views/users/partials/users_list.blade.php

@foreach($users as $user)
<tr>
    <td>{{ $user->name }}</td>
    <td>{{ $user->email }}</td>
</tr>
@endforeach
Enter fullscreen mode Exit fullscreen mode

Step 3: Implementing jQuery for Infinite Scroll

Now, modify your jQuery script to support infinite scroll:
public/js/infinite-scroll.js

$(document).ready(function() {
    let page = 1;

    $(window).scroll(function() {
        if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
            page++;
            loadMoreData(page);
        }
    });

    function loadMoreData(page) {
        $.ajax({
            url: '?page=' + page,
            method: 'GET',
            beforeSend: function() {
                $('#loading').show();
            },
            success: function(data) {
                if (data.trim() === "") {
                    return;
                }
                $('#loading').hide();
                $('#user-list').append(data);
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
    }
});
Enter fullscreen mode Exit fullscreen mode

Include this script in your main view:

@section('scripts')
<script src="{{ asset('js/infinite-scroll.js') }}"></script>
@endsection`
Enter fullscreen mode Exit fullscreen mode

By implementing infinite scroll with Laravel and jQuery, you can provide a smoother user experience. This approach eliminates the need for pagination links and automatically loads content as the user scrolls.

Enjoy!

Comments 2 total

  • Nicolus
    NicolusAug 23, 2024

    I like that you made a simple jQuery version and not just the Vue version : Even though Vue (or maybe Alpine) is a better approach for any sizeable project it's good to know that you can also make a minimal version with just a few lines of javascript.

    Come to think of it, it could probably be done almost as easily without jQuery and only native javascript with fetch(), document.getElementById(), and classList.toggle() to change the visibility of the loader.

    • Rafa Rafael
      Rafa RafaelAug 23, 2024

      Thanks for the feedback! I’m glad you liked the simple jQuery version. I agree—Vue or Alpine is better for bigger projects, but it’s useful to have a minimal option too. You’re right, it could definitely be done with native JavaScript using fetch(), getElementById(), and classList.toggle(). I’ll keep that in mind!

Add comment