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.

Contents

  • 1 Prerequisites
  • 2 Create Project For Pagination in Laravel 8
  • 3 Create and Configure Database
  • 4 Create a Model and Migration
  • 5 Add Mass Assignment in User Model
  • 6 Set Fields in Factory Class For Dummy Records
  • 7 Insert Dummy Records Using Tinker
  • 8 Create a Controller For Pagination in Laravel 8
  • 9 Create a Route
  • 10 Create a View For Displaying Pagination in Laravel 8
  • 11 Conclusion

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.

create-project
composer create-project --prefer-dist laravel/laravel pagination

The Laravel 8 project setup will take a couple of minutes.

Create new project in laravel 8
Create new project in laravel 8

After finishing the installation, let’s create a database in MySQL.

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
CREATE DATABASE laravel8_pagination;

I have created the database, now let’s connect to our application.

.env
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.

create_users_table.php
<?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.

migrate-tables
php artisan migrate

Here, all the tables are migrated into the database.

Migrated Tables
Migrated Tables

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.

User.php
<?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.

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.

UserFactory.php
<?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.

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.

tinker command - insert dummy records
php artisan tinker
User::factory()->count(500)->create()

The above command will create the 500 dummy records in the users table.

Dummy Records Inserted

Dummy Records Inserted

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.

create-controller
php artisan make:controller

The controller has been created. Now, put the functionality for implementing the pagination in laravel 8.

UserController.php
<?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.

#laravel #web-development #php #developer #programming

How to Create Pagination in Laravel 8 with Eloquent
4.60 GEEK