Implementing Infinite Scroll with Laravel and jQuery
Rafa Rafael
Posted on August 22, 2024
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'));
}
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
resources/views/users/partials/users_list.blade.php
@foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
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);
}
});
}
});
Include this script in your main view:
@section('scripts')
<script src="{{ asset('js/infinite-scroll.js') }}"></script>
@endsection`
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!
Posted on August 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.