Pagination in Laravel

By CodersDrive
21-Jun-2020
Laravel

When you want to fetch more records in any web application it is always better to paginate records to avoid delay in page loading. Laravel has pagination function enabled out of the box. You can use this feature in a simple way.

Step-1 Create a Model and Migration

First create a Model Client and its migration using the following command.

php artisan make:model Client -m

This command will generate Client.php Model Class at app/ path and its migration file 2020_mm_dd_xxxxxx_create_clients_table.php at database/migrations/ path. This migration file has the table column names, you can edit this file and add our required columns as shown below.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateClientsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return  void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->id();
            $table->string('firstName');
            $table->string('lastName');
            $table->string('email');
            $table->string('phoneNumber');
            $table->string('address');
            $table->string('city');
            $table->string('country');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return  void
     */
    public function down()
    {
        Schema::dropIfExists('clients');
    }
}

In this example we have added 7 fields to this migration file ('firstName', 'lastName', 'email', 'phoneNumber', 'address', 'city', 'country'). Now run the following command to create "clients" table in your MySQL DB.

php artisan migrate

Now you can verify the created clients table logging into your MySQL DB.

Step-2 Make Model fields fillable

As Laravel works on MVC (Model View Controller) type architecture, for security reasons when ever a Model is created by default all the fields are not allowed to add data through Controllers. To enable this we have to edit the created Model Client at app/ location and edit the code as shown below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $guarded = [];
}

In the code shown protected $guarded = []; means no Model fields are guarded, hence all the table coulmns can be updated through Controllers. If we want to protect some columns not to be allowed for add/update through Controllers you can add them under "$guarded" array like this protected $guarded = ['address'];.

There is also otherway to protect using protected $fillable = ['firstName','lastName'];. Which means only 'firstName', 'lastName' fields are allowed to add/update through Controller.

Now you can add clients data to this table or you can generate fake data for development purpose as per below link.

Step-3 Add Route to show clients

Create a route and append the following code to web.php file at routes/ location.

Route::get('/show-clients', 'ClientController@show');

When this url is accessed show() function under ClientController will be called. So, you have to create this controller.

Step-4 Create Clients Controller

Now create a Controller to manage data access from clients table to your application using the following command.

php artisan make:controller ClientController

Open the file ClientController.php created at path app/Http/Controllers/ and add the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Client;

class ClientController extends Controller
{
    public function show()
    {
        $clients= Client::paginate(5);
        return view('show-clients', compact('clients'));
    }
}

In this code $clients= Client::paginate(5); denotes to retrieve 5 client records when executed. This $clients data is return to show-clients page. So, we have to create this page now.

Step-5 Create Show Clients Page

Now create a page show-clients.blade.php at resources/views/ and add the following code.

@extends('layouts.app')
@section('content')
<?php $l=1; ?>
<div class="container text-center">
<h1 class="text-center">Laravel pagination demo</h1>
<table class="table table-bordered table-hover table-sm table-striped">
<thead><th>S.No</th><th>Client Name</th><th>Email</th><th>Phone.No</th><th>Address/Location</th></thead>

<tbody>
@foreach($clients as $client)
<tr>
<td>{{$l++}}</td>
<td>{{$client->firstName}} {{$client->lastName}}</td>
<td>{{$client->email}}</td>
<td>{{$client->phoneNumber}}</td>
<td>{{$client->address}},<br>{{$client->city}},<br>{{$client->country}}</td>
</tr>
@endforeach
</tbody>

</table>
{{$clients->links()}}
</div>

@endsection

Here to display pagination links we have added {{$clients->links()}}. This will create links based on total records available. You can see a demo of this page using below link.

Demo

Laravel Php

Search blog..!

Connect with us