In Laravel, pagination is a feature that allows you to divide a large dataset into smaller chunks or pages. It makes it easier to display and navigate through data in a web application. The pagination in Laravel 10 provides a convenient way to implement this functionality. It automates the process of splitting data, generating pagination links, and managing the user’s interactions with the paginated data. The pagination helps improve the user experience. It breaks down a large amount of content into smaller portions. It makes it easier to digest. Also, it reduces scrolling and loading times and makes the interface more user-friendly. You can create pagination in Laravel 10 by fetching data into chunks using paginate() function. This is the functionality part, but for rendering that pagination at the UI end, it will be done using Bootstrap.
Prerequisites
We are going to create Bootstrap pagination in Laravel 10. Hence, it is recommended to have a Laravel 10 application setup to proceed with this post.
However, in order to have a Laravel 10 project, your system must need the below tools and configurations.
- PHP >=8.1
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Once, you are ready, let’s proceed with the project setup.
How to Use Tailwind CSS in Laravel 10 For Interactive Designs
Step 1 – Create a Project to Implement Pagination in Laravel 10
In the very first step, you need to create a project setup in Laravel 10. Hence, open the terminal and hit the below command.
composer create-project --prefer-dist laravel/laravel blog-app
After having the project setup, let’s configure the database.
Step 2 – Configure Database
For the database setup, you will require a database. We are using MySQL to create a database for this post. Once, you are done, navigate to the .env file and add the DB credentials as shown.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_pagination
DB_USERNAME={{ DATABASE_USERNAME }}
DB_PASSWORD={{ DATABASE_PASSWORD }}
After having the DB configuration, you will need a model and migration to communicate with the database. Therefore, let’s create these files.
How to Create and Use Custom Helper Function in Laravel 10
Step 3 – Create a Model, Migration, and Controller
For creating the model and migration you can use an artisan command inside the project.
This step is optional for this post because by default a model and migration will be available in the Laravel project. However, you can create another if needed.
I am going to create a new model named Employee.
php artisan make:model Employee -mc
After creating the Model and migration, you will have to add the schema. Hence, navigate to the employees migration and add the schema as shown below.
<?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('employees', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('email')->nullable();
$table->string('phone_number')->nullable();
$table->string('address')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('employees');
}
};
Next, you will have to create a factory class for dummy records for applying pagination.
Step 4 – Create a Factory Class For Creating Dummy Records
We will be using the faker() class for generating some dummy records for employees.
Hence, create a factory class using the below command.
php artisan make:factory EmployeeFactory --modal=Employee
After creating the factory class, let’s add the attributes which are defined in the table schema.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Employee>
*/
class EmployeeFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'phone_number' => fake()->phoneNumber(),
'address' => fake()->address(),
];
}
}
Once, you are done, let’s move to the next step for autoloading the dependencies.
Get the Last Inserted Id in Laravel 10 Using Different Methods
Step 5 – Autoload Laravel Dependencies
Next, will run the composer dump-autoload command in order to load the dependencies.
composer dump-autoload
This command will generate new optimized autoload files.
Thereafter you will have to run the factory class using the Tinker command.
Step 6 – Run Employee Factory Class Using Tinker
We haven’t generated employee dummy records yet for Bootstrap pagination in Laravel 10. So, in order to run the factory create command, we need tinker command line interaction.
So, let’s do that using the below command.
php artisan tinker
Employee::factory()->count(200)->create()
In the above command, we have defined the number of records to be created in the count function. Therefore, it will insert 200 records in the employees table.
We have sufficient data in order to apply the pagination. Hence, let’s move to the functionality part.
Auth Scaffolding Using Jetstream with Intertia Js in Laravel 10
Step 7 – Create Functionality to Fetch Data in Paginate
We already created a controller. Therefore, let’s add the below snippet to fetch the data from the Employee model through eloquent.
<?php
namespace App\Http\Controllers;
use App\Models\Employee;
use Illuminate\Http\Request;
class EmployeeController extends Controller
{
/**
* Function : Get Employees
* @param NA
* @return response
*/
public function index() {
$employees = Employee::paginate(10);
return view('employee', compact('employees'));
}
}
I have fetched the data in paginated by defining the number of rows per page. Also, I have returned the records into a view.
Step 8 – Create a View For Rendering Bootstrap Pagination in Laravel 10
Inside the views folder, create a blade file named employee.blade.php. After that add the below snippet to render employees record in tabular form.
I have used Bootstrap CDN for easy UI formation.
<!doctype html>
<html lang="en">
<head>
<title>Pagination in Laravel 10 Using Bootstrap</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<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">
<style>
.pagination {
float: right;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container-fluid px-5 pt-3">
<h4 class="text-center fw-bold border-bottom pb-3"> Pagination in Laravel 10 Using Bootstrap </h4>
<div class="table-responsive pt-5">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Address</th>
</tr>
</thead>
<tbody>
@forelse ($employees as $employee)
<tr>
<td>{{ $employee->id }} </td>
<td>{{ $employee->name }} </td>
<td>{{ $employee->email }} </td>
<td>{{ $employee->phone_number }} </td>
<td>{{ $employee->address }} </td>
</tr>
@empty
<tr>
<td colspan="6">
<p class="text-danger">No data found </p>
</td>
</tr>
@endforelse
</tbody>
</table>
{{ $employees->links() }}
</div>
</div>
<!-- Bootstrap JavaScript Libraries -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous">
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js"
integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous">
</script>
</body>
</html>
Next, you need a route to check this pagination.
Auth Scaffolding Using Jetstream with Livewire in Laravel 10
Step 9 – Create a Route For Rendering Pagination
Add a new route in the web.php file for rendering the data with the pagination.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;
Route::get('employees', [EmployeeController::class, 'index']);
That’s it with the functionality part. Now, the application is ready to run and paginate the data.
php artisan serve
Hence, in order to check the result open the browser and navigate to the URL.
That’s all for this post. If you have any queries or suggestions regarding this post then please let me know in the comment section below. It will be highly appreciated.
Leave a Reply