It is very easy to implement the feature of displaying data in the view on infinite page scroll in Laravel 11 Livewire application, for this you need to create loadMore() method on the component and use it on the views.
Let’s start building the page in a Laravel livewire application to display data by infinite scrolling the page:
Step 1: Set Up Livewire
Run the following command to install and set up livewire in application:
composer require livewire/livewire
Step 2: Create Infinite Scroll Component
Run the following command to create the component for infinite page scroll:
php artisan make:livewire load-more-user-data
Step 3: Implement Infinite Page Scroll
Edit app/Livewire/LoadMoreUserData.php
file and implement infinite page scroll logic in it to pass data on view:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\User;
class LoadMoreUserData extends Component
{
public $limitPerPage = 10;
protected $listeners = [
'load-more' => 'loadMore'
];
public function loadMore()
{
$this->limitPerPage = $this->limitPerPage + 6;
}
public function render()
{
$users = User::latest()->paginate($this->limitPerPage);
$this->emit('userStore');
return view('livewire.load-more-user-data', ['users' => $users]);
}
}
Edit resources/views/livewire/load-more-user-data.blade.php
and display the data in the view on infinite scroll:
<div>
<table class="table table-striped">
<thead>
<tr>
<th>#Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
Step 4: Create Route
In routes/web.php
file, create routes for infinite page scroll:
Route::get('/load-more-users', function () {
return view('welcome');
});
Step 5: Import Livewire Component in Blade
Edit resources/views/welcome.blade.php
file, and import livewire infinite page scroll component in it:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel 11 Livewire Infinite Page Scroll Tutorial - Itcodstuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
html,
body {
height: 99vh;
}
</style>
</head>
<body>
<div class="container mt-5">
@livewire('load-more-user-data')
</div>
@livewireScripts
<script type="text/javascript">
window.onscroll = function (ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
window.livewire.emit('load-more');
}
};
</script>
</body>
</html>
Step 6: Test Application
Run the following command to start laravel application server:
php artisan serve
Enter http://localhost:8000/load-more-users
url on browser for testing.