You always required pagination for handling a large number of data. If you want to split data into chunks then the pagination is the best way. It breaks down the total number of records in chunks per page. It provides the option to navigate to the next and previous page. Hence, you can have access to the entire data listed out on the page. The pagination allows flexibility to manage the records. You can set the data limit per page. Also, you can set the offset based on the current page. You can create pagination in Laravel 8 using the eloquent. To create the pagination in Laravel 8 you can use the eloquent function. It makes it a simple approach for splitting the records. Today, I will create the pagination in Laravel 8 with eloquent.
Prerequisites
Before creating a new application in Laravel 8, You will require the following tools. I will use the VS Code editor. You can use any other code editor as per your choice.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
So, let’s create the project. For creating the project, I will use the composer.
Create Project For Pagination in Laravel 8
You can create the project by hitting the composer command in the terminal.
composer create-project --prefer-dist laravel/laravel pagination
The Laravel 8 project setup will take a couple of minutes.
After finishing the installation, let’s create a database in MySQL.
How to Use Guzzle Http in Laravel 8 For Request Handling
Create and Configure Database
For implementing the pagination in Laravel 8, we will need a database. Hence, for the database, I will use MySQL. You can use the MySQL command line or the phpMyAdmin.
CREATE DATABASE laravel8_pagination;
I have created the database, now let’s connect to our application.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel8_pagination
DB_USERNAME=root
DB_PASSWORD=root
Now, database is configured and our application is ready for the next step.
Create a Model and Migration
For listing out the data for the pagination in Laravel 8, we will require a model. In this step, we will create a model and a migration file. The migration file will contain the table schema for the database. The model will have the fillable data based on table schema. Also, we will use the eloquent to make a query from the database.
You can create a new model and migration or can use the default one. But, I will use the default one that is the User model and its migration. So, we will set the Laravel pagination of the user’s data.
Firstly, we’ll set up the migration. I have added some additional fields here.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone')->nullable();
$table->string('address')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Now, migrate the tables using the below command.
php artisan migrate
Here, all the tables are migrated into the database.
How to Implement Yajra DataTables in Laravel 8
Add Mass Assignment in User Model
As per the migration, we will have to set the mass assignment in the fillable data. Actually, we will create dummy records using the factory class. And we’ll fetch the data from the users table for the pagination in Laravel 8. That is why it will require to specify the fillable fields.
<?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;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'phone',
'address'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Now, we have set the fillable data in the User model. In the next step, we’ll have to set the fields in the factory class that will gonna insert.
How to Send Emails Using Twilio Sendgrid in Laravel 8
Set Fields in Factory Class For Dummy Records
There is the default factory class for the User. So, we have to set the fields here. The specified fields will gonna insert as a dummy records using the faker class.
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'phone' => $this->faker->phoneNumber,
'address' => $this->faker->address,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
}
Now, we will have to trigger the command for inserting the dummy records.
How to Send Email Using Mailgun in Laravel 8
Insert Dummy Records Using Tinker
Basically, we will implement the pagination in Laravel 8 on the data. So, if I will insert it manually then it will take the time. Therefore, I will use the tinker class. The tinker class will take the input for the number of records that which will gonna insert. This will call directly to the model and the model is linked with the table.
php artisan tinker
User::factory()->count(500)->create()
The above command will create the 500 dummy records in the users table.
Create a Controller For Pagination in Laravel 8
We can write the logic to fetch the data in a chunks in the controller. The chunks data will create the pagination in Laravel 8. After fetching the data from the table, we will return it to the view. So, let’s create a controller first.
php artisan make:controller
The controller has been created. Now, put the functionality for implementing the pagination in laravel 8.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index() {
$users = User::paginate(10);
return view("users", compact('users'));
}
}
In the above snippet, I have included the User model in the namespace. then created a function and inside the function, I have paginated the 10 records. It will break down the entire records in the limit of 10.
Create Auth Using Jetstream and Intertia js in Laravel 8
Create a Route
You will need to create a route for the above function. So, this route will be added in the web.php file.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get("users", [UserController::class, "index"]);
We have the route, now, we will create a view on which the data will be loaded with the pagination.
Laravel 8 Ajax CRUD Application Tutorial For Beginners
Create a View For Displaying Pagination in Laravel 8
I will create a view with the name users.blade.php. Because I have returned the users data into this view that I have written in the controller.
In the view, I will use the Bootstrap for the basic layout design.
<!doctype html>
<html lang="en">
<head>
<title> Laravel 8 Pagination | Programming Fields </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container-fluid mt-4">
<h3 class="text-center pb-4 font-weight-bold"> Laravel 8 Pagination - Programming Fields </h3>
<table class="table">
<thead>
<th> Id </th>
<th> Name </th>
<th> Email </th>
<th> Phone </th>
<th> Address </th>
<th> Created at </th>
</thead>
<tbody>
@foreach($users as $user)
<tr>
<td> {{$user->id}} </td>
<td> {{$user->name}} </td>
<td> {{$user->email}} </td>
<td> {{$user->phone}} </td>
<td> {{$user->address}} </td>
<td> </td>
</tr>
@endforeach
</tbody>
</table>
{{$users->links()}}
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Save and run the application. Open the URL in the browser that is –
localhost:8000/users
As the result, you will have the below screen. Here, the data has paginated in the limit of 10. But there is a design issue, which means navigation icons are not in the sequence. And we are not expecting the pagination in Laravel 8 like this.
So, can we solve it? Yes, we can solve it without writing any CSS in the view.
Actually, we are using Bootstrap CDN in the view. So, Laravel provides the facility to manage the pagination using the Bootstrap. Also, it can be managed using the Tailwind CSS. But, when we will install the Tailwind CSS, then we can use it.
So, we will have to write a provider in the AppServiceProvider.php. Here, I have passed the Bootstrap Paginator as showing below.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// used for bootstrap pagination design
Paginator::useBootstrap();
}
}
You can take a look at the Laravel 8 Documentation. Now, refresh the page and see the result.
Yeah, we have the beautiful design for the pagination. And all the links are working and clickable. That’s the feature of the pagination in Laravel 8.
Conclusion
Laravel provides a eloquent method to paginate the records as per the limit. We set the number of records that we want in per page. In this tutorial, we have implemented the pagination in laravel 8 on the dummy data. The dummy data had created using the factory class. In the factory class, we set the fields for which we want the dummy records. Then using the tinker class, we executed the number of records to be insert. For managing the pagination design, we used the Bootstrap. You can manage the pagination style using the Tailwind CSS. Laravel provides these options. So, I hope you will find it a helpful post for you.
Leave a Reply