The user experience plays a pivotal role in any web application. Web applications that are dynamic, responsive, and easy to navigate tend to stand out. Users expect websites and applications to load quickly, display information seamlessly, and allow for smooth navigation. Laravel has been at the forefront of simplifying web development. With the Laravel 10, developers are presented with even more powerful tools to create dynamic and interactive web applications. One such tool is Livewire, a full-stack framework that facilitates real-time interactivity without extensive JavaScript coding. One of the important features of Livewire is Livewire pagination. Therefore, in this step-by-step guide, we will delve into the Livewire Pagination in Laravel. Also discover how it can make your web app truly dynamic and responsive.
We are going to implement the Livewire pagination in Laravel. Let’s quickly take a look at the result that we are going to achieve in the example.
Prerequisites
To proceed with this Livewire Pagination in Laravel, you will have to follow the below prerequisites.
- PHP >=8.1 – If you are implementing in Laravel 10 then you will require this.
- Composer – For dependency manager.
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
- Basic Understanding – You require some basic understanding of Laravel.
Once you are done, let’s quickly do the project setup in Laravel 10.
Recommended: Building a Dynamic Livewire CRUD Application in Laravel 10
Step 1 – Create a Laravel Project Setup For Livewire Pagination
To install the Laravel, you will have to hit the below command.
composer create-project --prefer-dist laravel/laravel laravel-livewire
Once the installation is done, you will have to set up the database. So, navigate to the project directory.
cd laravel-livewire
After that, look at the .env file and add the DB credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_livewire
DB_USERNAME=root
DB_PASSWORD=root
Once you have configured the database, next, you will have to install Livewire in your project. Hence follow the next step.
Recommended: Livewire Form Validation: Building Better User Experiences in Laravel
Step 2 – Install Livewire in Laravel 10
In order to install Livewire, you will have to hit the below command in the terminal.
composer require livewire/livewire
After the successful installation, you can move to the next step. Next, you will have to create a model and migration for implementing the Livewire Pagination in Laravel 10.
So, let’s do that quickly.
Step 3 – Model and Migration Setup in Laravel
In case, if you don’t want to go with the default Model and Migration of Laravel then you can create a new one. In this case, I am moving ahead with the default Model and Migration that is for the users.
Hence, let’s add the below schema in the user table migration.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};
Also, you will be required to add the fillable data in this respective model.
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
Thereafter, you will have to migrate the database schema. So that the DB will have the updated table schemas.
php artisan migrate
Next, you will require a Livewire component.
Recommended: Getting Started with Laravel Livewire : A Comprehensive Guide for Beginners
Step 4 – Create a Livewire Component For Pagination
Now, it’s time to generate a Livewire component that will take care of the pagination logic. We are going to implement the user listing having pagination. Hence, we required a Livewire component.
Therefore, run the following command.
php artisan make:livewire UserManagement
The above command will create a Livewire component in which there will be two files. One file will be for the class file and another for the blade file.
Now, it’s time to add the logic to implement the Livewire pagination.
Step 5 – Add Livewire Pagination Logic
So, initially, navigate to the class file (component) that will be located in the app/Http/Livewire directory. After that, you will have to add the below snippet.
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
use Livewire\WithPagination;
class UserManagement extends Component
{
// Calling WithPagination Trait
use WithPagination;
// Apply Bootstrap Theme for Pagination
protected $paginationTheme = 'bootstrap';
public function render()
{
// Paginating users data in chunks
$users = User::paginate(10);
// Rendering data to the View
return view('livewire.user-management', compact('users'));
}
}
Let me quickly walk you through the above snippet.
- At the very top, I have imported one Trait provided by Livewire. That is WithPagination.
- After that inside the class, I invoked that trait.
- Next line, I have used the paginationTheme property provided by Livewire itself. Laravel, Livewire’s default pagination view uses Tailwind classes for styling. If you use Bootstrap in your application, you can enable the Bootstrap theme for the pagination view using the
$paginationTheme
property on your component. - Lastly, I have fetched the data through the User model and rendered that to the component blade file.
Recommended: Scaling Laravel Apps with Efficient Many-to-Many Relationships
Step 6 – Design User Interface for Pagination in Livewire
We will be applying pagination in a tabular layout. Hence, you will require a HTML table element for this. Also, you will require Bootstrap for some basic style component.
So, navigate to the component blade file (user-management.blade.php) available in resources/views/livewire directory. After that, simply add the below snippet there.
<div>
<div class="card shadow mt-3">
<div class="card-body">
<div class="table-responsive mt-3">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@forelse ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>
{{ $user->name }}
</td>
<td>
{{ $user->email }}
</td>
<td>
<button class="btn btn-info btn-sm">View</button>
<button class="btn btn-success btn-sm">Edit</button>
<button class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
@empty
<tr>
<td colspan="6" align="center">
<span class="text-danger"> No Records Found </span>
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
{{ $users->links()}}
</div>
</div>
<style>
.pagination {
float: right;
}
</style>
</div>
Livewire Pagination is ready to render the data and split out into chunks. But, you will have to render this Livewire component in a Laravel blade file first.
Hence, let’s render this Livewire component.
Step 7 – Render Livewire Component in Laravel
For rendering the Livewire component in Laravel, you will require a blade file. However, you can render it directly into the route itself just like the Laravel blade.
But, in this case, I am going to render it through a view. So, firstly I will create a controller, and through the controller, I will render a Laravel blade file. Then inside that blade file, I will call the Livewire component.
php artisan make:contoller UserController
After having the controller, let’s add the below function.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index() {
return view('users');
}
}
In the above function, I have rendered a blade file named users. Hence, let’s create it.
But, after having the users.blade view, you will have to add the below HTML snippet.
<!doctype html>
<html lang="en">
<head>
<title>Livewire Pagination in Laravel 10</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{{-- Bootstrap CSS v5.2.1 --}}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
{{-- Livewire Styles --}}
@livewireStyles
</head>
<body>
<main class="pt-3 px-5">
<div class="container-fluid">
<h3 class="text-center fw-bold border-bottom pb-2">Livewire Pagination in Laravel 10 </h3>
<div class="row justify-content-center mt-3">
{{-- Calling Livewire Component --}}
@livewire('user-management')
</div>
</div>
</main>
{{-- jQuery CDN --}}
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
{{-- Bootstrap JavaScript Libraries --}}
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js"></script>
{{-- Livewire Scripts --}}
@livewireScripts
</body>
</html>
The above blade file contains the Livewire styles and scripts. Also, I have used Bootstrap for applying inbuilt styling for the component.
Now, next, you require a route.
Recommended: Advanced Eloquent Relation with hasManyThrough in Laravel 10
Step 8 – Add Route For Livewire Pagination in Laravel
To add the route, you will have to navigate to the web.php file. After that, you will have to add the route as shown below.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get('users', [UserController::class, 'index'])->name('users');
That’s it. Now, the Livewire pagination functionality is done.
But, you required some data to test this flow. It is good, if you have the data for the testing purposes. However, we can create some fake data through factory and seeder as well.
Step 9 – Create Fake Data Using Factory and Seeder in Laravel
This step is optional, if you have the data to check the flow. Default, you will have the UserFactory class. Hence, simply replace the definition with the below snippet.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
Rest work will be done by the seeder for seeding the fake data into the users table.
Hence, navigate to the DatabaseSeeder.php file and define the number of records that you want to create in the database.
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
\App\Models\User::factory()->count(100)->create();
}
}
So, I have defined count as 100 in the above snippet. Now, you will have to seed it using the below command.
php artisan db:seed
On successful seed, it will insert the specified count records in the users table.
Now, you are on rock to run the application and test the result.
So, the main difference of using Livewire pagination is it won’t refresh the page on page change. But, Laravel does. That’s the power of Livewire in Laravel.
Bottom Lines
Congratulations! You have successfully implemented Laravel 10 Livewire Pagination into your application. This combination of Laravel and Livewire empowers you to create dynamic and responsive web applications with unparalleled ease. The flexibility is in your hands – you can customize the pagination by adjusting the number of items per page, styling the pagination links, and more to tailor it to your project’s specific requirements.
Leave a Reply