Implementing Infinite Scroll with Laravel and jQuery

Rafa Rafael - Aug 22 - - Dev Community

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!

. . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player