Laravel Eloquent: How to create ‘infinity scroll’ pagination

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

Laravel Eloquent makes handling database interactions seamless and simple. Adding a modern user interface feature like infinite scroll not only enhances the user experience by providing a smooth way to load data but also can be key to handling large datasets efficiently. In this tutorial, we’ll walk through creating an infinite scroll pagination utilizing Laravel’s Eloquent ORM.

Implement Infinite Scrolling in Laravel & Eloquent

Infinite scrolling is a web-design technique that loads content continuously as the user scrolls down the page, eliminating the need for pagination. While a traditional pagination system divides content into discrete pages, infinite scrolling dynamically appends new content onto the existing page as the user reaches the bottom.

Basic Infinite Scroll with Eloquent

Let’s start with a simple example of infinite scrolling. We will assume that you have a Laravel project set up with a model called Post and a corresponding database table.

use App\Models\Post;

// Controller method
public function index()
{
    $posts = Post::latest()->paginate(10);
    
    if (request()->wantsJson()) {
        return $posts;
    }
    
    return view('posts.index', compact('posts'));
}

This code checks if the request wants a JSON response (likely an AJAX request from scrolling) and returns the paginated posts accordingly, else it returns the view with posts data.

Setting Up the Frontend

Frontend wise, you’ll need some JavaScript to detect when the user has scrolled to the bottom of the page and then perform an AJAX request to load more content.

// JavaScript (using jQuery for simplicity)
$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() =={()=>' { 
    
    const page = '{'+ $(taget).attr('+')data('next-page'+')+'';
    
    if (page !== null) {
        loadMoreData(page);
    }
}'});

function loadMoreData(page){
  $.ajax(
        {
            url: page,
            type: 'get',
            beforeSend: function()
            {
                $('.ajax-load').show();
            }
        })
        .done(function(data)
        {
            if(data.html == " "){
                $('.ajax-load').html("No more records found");
                return;
            }
            $('.ajax-load').hide();
            $('#post-data').append(data.html);
        })
        .fail(function(jqXHR, ajaxOptions, thrownError)
        {
              alert('server not responding...');
        });
}

Enhancing Performance with Lazy Loading

To optimize performance, especially with image-heavy content, you might employ lazy loading alongside infinite scroll. By doing so, only visible content is loaded, and the rest is deferred until needed.

Advanced Implementation

In more advanced scenarios, you might need to customize the query used for pagination or implement additional features like filter or sort. You can customize the Eloquent query as needed and follow a similar pattern to add these enhancements to your infinite scroll functionality.

// Example with customized query and sorting
public function index()
{
    $posts = Post::when(request()->has('sort'), function ($query) {
            return $query->orderBy('title', request('sort'));
        })->paginate(10);
    // ... (rest of the controller method)
}

You’d need additional JavaScript to handle these additional query parameters and pass them along with your AJAX requests for new pages.

Conclusion

In conclusion, infinite scrolling is a user-friendly feature that can be easily integrated into a Laravel application using Eloquent for a seamless data retrieval experience, Keep in mind that it is important to consider SEO and accessibility when implementing this feature.