Hello Devs,
In this tutorial, we will learn Laravel Livewire Load More Example
Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.Livewire relies solely on AJAX requests to do all its server communicaton
Follow this step by step guide below.
Step 1 : Install Laravel App
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Setup Database Configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password
Step 3 : Install Livewire
composer require livewire/livewire
Step 4 : Create Component
php artisan make:livewire users
Create files on both of this path:
app/Http/Livewire/Users.php
resources/views/livewire/users.blade.php
app/Http/Livewire/Users.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\User;
class Users extends Component
{
public $perPage = 8;
protected $listeners = [
'load-more' => 'loadMore'
];
public function loadMore()
{
$this->perPage = $this->perPage + 5;
}
public function render()
{
$users = User::latest()->paginate($this->perPage);
$this->emit('userStore');
return view('livewire.users-list',['users' => $users]);
}
}
Step 5 : Add Route
routes/web.php
Route::view('users','livewire.home');
Step 6 : Create View
resources/views/livewire/users.blade.php
<div>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>No.</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>
</div>
resources/views/livewire/home.blade.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="{{ asset('js/app.js') }}" defer></script>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
@livewireStyles
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h2>Laravel Livewire Load More with Scroll - rathorji.in</h2>
</div>
<div class="card-body">
@if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
@endif
@livewire('users')
</div>
</div>
</div>
</div>
</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>
Run this command for a peek
php artisan serve
Open this URL in your browser,
http://localhost:8000/users
May this example help you.