Laravel 8 Tutorial - Livewire Pagination
In this tutorial, we are going to learn about Livewire Pagination. So, let's see how to create pagination in Livewire.
First, let's create a new component. Switch to the command prompt and run the following command:
php artisan make:livewire Users
Now, run the application:
php artisan serve
Now, switch to the project and let's create the route for this component. Just go inside the routes directory and open the web.php file. Now, add the route:
Route::get('/all-users',Users::class);
Next, open the Users.php component class file and write the following code:
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;
class Users extends Component
{
use WithPagination;
public function render()
{
$users = User::paginate(5);
return view('livewire.user-component',['users'=>$users]);
}
}
Save the file and now open the users.blade.php view file. Create a table and write the following code:
<div>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
All Users
</div>
<div class="card-body">
<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>
</div>
</div>
</div>
</div>
</div>
To add the pagination links after the closing table tag, write the following code:
{{$users->links()}}
One more thing, add CSS for pagination:
<style>
nav svg{
height: 20px;
}
</style>
All done! So, let's check this. Switch to the browser and go to the URL /all-users.
And here, you can see the 5 records inside the table and the pagination link. So, in this way, we can create Livewire Pagination. That's all about Livewire Pagination.