AppDividend
Latest Code Tutorials

Laravel 9 Pagination: The Complete Guide

Pagination in Laravel is effortless because it provides the paginate() method.  When we have thousands of rows in the database, then pagination will be needed.

Laravel Pagination

To create pagination in Laravel, use the paginate() method on the query builder or an Eloquent query. The paginate() method sets the proper limit and offsets based on the current page, which the user is viewing. Laravel’s paginator is out of the box with the query builder and Eloquent ORM and includes database results. The HTML generated by a paginator is compatible with the Bootstrap CSS framework.

By default, the current page is detected by a value of the page query string argument on the HTTP request. This value is automatically detected by the Laravel and automatically inserted into links generated by the paginator.

If Laravel provides something from scratch, then please don’t create your approach. For example, people often create their code for pagination, which is wrong. Instead, use Laravel’s helper method, which is a clean way.

Now, let’s see the Pagination in Laravel Tutorial in action.

First, we install Laravel and then fake some data with the faker library.

Step 1: Install Laravel 9

Type the following command.

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

Now, set up a database in the .env file.

Okay, next, go to the terminal and hit the following command.

php artisan migrate

It will create the two tables in the database. Now, we are using the faker library to populate the data in the database.

Step 2: Generating fake data in the database.

If you wonder how to install it, good news – it’s already established for you in Laravel!

Take a look at a default composer.json of Laravel.

 "require-dev": {
        "filp/whoops": "~2.0",
        "nunomaduro/collision": "~1.1",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "~1.0",
        "phpunit/phpunit": "~7.0",
        "symfony/thanks": "^1.0"
},

Now, we need to write the 6-7 lines of code to generate fake users’ data. Go to the database  >>  seeds  >> DatabaseSeeder and add the following lines of code to it.

// DatabaseSeeder.php

/**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();
    	foreach (range(1,1000) as $index) {
	        DB::table('users')->insert([
	            'name' => $faker->name,
	            'email' => $faker->email,
	            'password' => bcrypt('secret'),
	        ]);
        }
    }

First, we have created the faker object and then loop through different columns of the users table and assign one property at a time.

Every time the loop was iterating, new random data is generated and attached to the particular columns.

So that is how we can make different fake data for each user. Now type the following command to create the fake data.

 php artisan db:seed

Now you can see in the database and the users’ table, there are lots of rows added.

The db:seed command runs this file called DatabaseSeeder.php.

Step 3: Display the data to the frontend.

Now, go to the HomeController.php file and in that create one function called getUsers().

// HomeController.php

use App\User;

public function getUsers()
{
    $users = User::all();

    return view('index', compact('users'));
}

Define the route inside a web.php  file.

// web.php

Route::get('/users', 'HomeController@getUsers')->name('users');

Finally, make one file inside resources  >>  views folder called index.blade.php.

<<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>Users Data</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link href="{{ asset('css/app.css') }}" rel="stylesheet" />
</head>
<body>
   <div class="container">
      <table class="table table-striped">
         <thead>
         <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
         </tr>
         </thead>
         <tbody>
            @foreach($users as $user)
            <tr>
               <td>{{ $user->id }}</td>
               <td>{{ $user->name }}</td>
               <td>{{ $user->email }}</td>
            </tr>
            @endforeach
         </tbody>
      </table>
   </div>
</body>
</html>

Right now, it displays all the rows, and that is what we want. We want to paginate the data. So let us do that.

Step 4: Paginating Eloquent Results

We need to use the paginate() function provided by the Eloquent model. So replace the method of all() to paginate() and pass the number of rows as a parameter.

// HomeController.php

$users = User::paginate(15);

Now, we need to display the pagination web component at the front end. As we have talked about earlier, Laravel’s pagination object works well with Bootstrap CSS Framework.

So, we need to add the following code to the table component inside the index.blade.php file.

{{ $users->links() }}

So, our whole index.blade.php file looks like this.

<<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>Users Data</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link href="{{ asset('css/app.css') }}" rel="stylesheet" />
</head>
<body>
   <div class="container">
      <table class="table table-striped">
         <thead>
         <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
         </tr>
         </thead>
         <tbody>
            @foreach($users as $user)
            <tr>
               <td>{{ $user->id }}</td>
               <td>{{ $user->name }}</td>
               <td>{{ $user->email }}</td>
            </tr>
            @endforeach
         </tbody>
      </table>
      {{ $users->links() }}
   </div>
</body>
</html>

Laravel Pagination Tutorial With Example From Scratch Converting Pagination Results To JSON

The Laravel paginator result classes implement the Illuminate\Contracts\Support\JsonableInterface contract and expose the methodmaking convertingrt your pagination results to JS is effortlessON.

So write the following code inside a web.php file.

Route::get('users', function () {
    return App\User::paginate(4);
});

So it will return as a JSON format data.Laravel Pagination Object So you can use this object and its metadata on the frontend to create pagination as per your requirement.

Conclusion

In other frameworks, pagination can be very painful. Laravel makes it a breeze. For using it, first, you have to make a change in your controller and call the paginate() method for fetching the data from the database and then inside the view, use the render() method to get the paginated data.

Laravel solves almost all the complex logic for us and saves time.

Recommended Posts

Laravel Collections Filter Method

Laravel Eloquent Collection

How To Create Multilingual Website using Laravel

Laravel Stripe Payment Gateway Integration

Laravel Cashier Braintree Payment Gateway

Laravel Validation

How To Export Data In Excel and CSV

Laravel PDF From View

Laravel Collections Search

Laravel Email Verification

9 Comments
  1. Pablo says

    Hi! Krunal

    I have followed several of your examples and they have been of a lot of help. But this one does not run from the beginning.

    First, I got: “Symfony\Component\Debug\Exception\FatalThrowableError : Class ‘Faker’ not found”

    Then, I add at the beginning: “use Faker\Generator as Faker;”
    But I got: “Symfony\Component\Debug\Exception\FatalThrowableError : Call to undefined method Faker\Generator::create()”

    Besides that, I have not created “HomeController.php”
    Can you give me a help, about it, please.

    1. Pablo says

      Problem solved!

      Looking into the subdirectory vendor. I found that I should use “Faker\Factory::create();” instead of “Faker::create();” in the file ‘database/seeds/DatabaseSeeder.php’. For HomeController.php, I just have to created with “php artisan make:controller HomeController”. Everything else is OK. Thanks!

  2. Trabajo Enlinea says

    great job! This was really helpful!

  3. Pardeep Kumar says

    Nice tutorial

    1. vinu says

      Display the data to the frontend.

  4. dicaredo says

    You have a github link?

  5. kaka isaac says

    Hi i get this error call to undefined function links() in the view
    Call to undefined method AppEmployee::links() (View: /home/izackk/Desktop/Payroll/resources/views/employee/index.blade.php)

    Here is my controller
    public function index()
    {
    //
    $employee = Employee::paginate(1);

    return view(“employee.index”)->with(’employee’, $employee);
    }

    my view

    @extends(‘layouts.app’)

    @section(‘content’)
    @if(count($employee)>0)

    Name
    Gender
    Phone
    Address
    TIN
    Profile Image
    Action

    @foreach($employee as $employee)

    {{ $employee->name }}
    {{ $employee->gender }}
    {{ $employee->phone }}
    {{ $employee->address }}
    {{ $employee->TIN }}
    {{ $employee->profileimage }}
    id }}”>EDIT
    id }}”>DELETE

    @endforeach

    {{ $employee->links() }}

    @else
    Employee not found
    @endif

    @endsection

  6. heber says

    Krunal,
    Nice, great post. Just a question:
    Is possible to add some information on paginations information? For example i’d like to add Request data given.

  7. Алекс says

    Thanks!!!!

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.