How to implement Pagination in Laravel 9 Livewire?

Livewire is full PHP based full stack framework which is included in Laravel 9 to help developers create dynamic webpages without learning Vue or React at first hand. Livewire actually sends AJAX based requests on runtime without using any AJAX script. We will create a simple Livewire Blog application to demonstrate the ease and power of Livewire. This will also have pagination implemented.

composer require livewire/livewire

Then we will create Livewire component.

php artisan make:livewire user-pagination

This must give us 2 files.

app/Http/Livewire/UserPagination.php
resources/views/livewire/user-pagination.blade.php

In “UserPagination.php” we will paste this code.

namespace App\Http\Livewire;
  
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\User;
  
class UserPagination extends Component
{
    use WithPagination;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render()
    {
        return view('livewire.user-pagination', [
            'users' => User::paginate(10),
        ]);
    }
}

Then in “user-pagination.blade.php” file we will write this code.

<div>
    <table class="table-auto" style="width: 100%;">
      <thead>
        <tr>
          <th class="px-4 py-2">ID</th>
          <th class="px-4 py-2">Name</th>
          <th class="px-4 py-2">Email</th>
        </tr>
      </thead>
      <tbody>
        @foreach ($users as $user)
            <tr>
            <td class="border px-4 py-2">{{ $user->id }}</td>
            <td class="border px-4 py-2">{{ $user->name }}</td>
            <td class="border px-4 py-2">{{ $user->email }}</td>
            </tr>
        @endforeach
      </tbody>
    </table>
  
    {{ $users->links() }}
</div>  

Then we will create a route in “web.php”.

Route::get('user-pagination', function () {
    return view('default');
});

After that, where we want to use this component, we will simple write this code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Example - codecheef.org</title>
    @livewireStyles
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.9.0/tailwind.min.css" integrity="sha512-wOgO+8E/LgrYRSPtvpNg8fY7vjzlqdsVZ34wYdGtpj/OyVdiw5ustbFnMuCb75X9YdHHsV5vY3eQq3wCE4s5+g==" crossorigin="anonymous" />
</head>
<body>
    
<div class="container">
    
    <div class="card">
      <div class="card-header">
        Laravel Livewire Example - Laramatic
      </div>
      <div class="card-body">
        @livewire('user-pagination')
      </div>
    </div>
        
</div>
    
</body>
  
@livewireScripts
  
</html>  

I hope this article will help you to understand Livewire. If you have any questions, please write in the comments section.