Laravel example for pagination data

The main of this blog is to create simple pagination which will work with a database.

For your better understanding, we have divided the program into some parts.

  1. Create Model And Migrations
  2. Create Controller
  3. Create Blade File
  4. Adding Routes
  5. Test Our Application

let's assume you have a Laravel application. If you don't have any application then create a new application and perform further steps into it.

Create Model and Migrations

In this example, we will display pagination data from the database so we need to create a database table. In Laravel, we need to create migration for creating database tables and models to access those data in effective ways.

To create a model and migration you need to enter the below command into a terminal :

php artisan make:model Data -mfs

Here, we have to pass additional parameters mfs M is for migrations, F is for factory, and S is for seeder. Those files will be used for generating dummy data for a database. Let's modify all files one by one.

database\migrations\2021_11_01_032504_create_data_table.php

<?php

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

class CreateDataTable extends Migration
{
    public function up()
    {
        Schema::create('data', function (Blueprint $table) {
            $table->id();
            $table->string('name');  //add this line
            $table->text('address'); //add this line
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('data');
    }
}

Now, we have to migrate our database. Enter the below command into the terminal :

php artisan migrate

This command will generate a Data table in our database. let's add some dummy data into our database using factory and seeder.

database\factories\DataFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class DataFactory extends Factory
{
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'address' => $this->faker->address()
        ];
    }
}

database\seeder\DataSeeder.php 

<?php

namespace Database\Seeders;

use App\Models\Data;
use Illuminate\Database\Seeder;

class DataSeeder extends Seeder
{
    public function run()
    {
        Data::factory()->count(100)->create();
    }
}

This alteration will apply logic for creating 100 dummy data while you run the below command.

php artisan db:seed --class=DataSeeder

Create Controller

Let's create a controller which will handle the operation for pagination and return view with data.

php artisan make:controller DataController

This command will create DataController.php. The new controller has only one method which will get all data from our model and return it to view. Let's make modifications for that :

app\Http\Controller\DataController.php

<?php

namespace App\Http\Controllers;

use App\Models\Data;
use Illuminate\Http\Request;

class DataContoller extends Controller
{
    public function index()
    {
        $data = Data::paginate(10);
        return view('data', compact('data'));
    }
}

Create View

In this step, we will create a view that will display data that passed through a controller to a user in table format with pagination links. For data display, we will use Bootstrap to style data and a table to display formatted data. Let's make changes to the view.

resource\views\data.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    </head>
    <div class="container">
        <h1>Laravel Pagination Example - Codewolfy.com</h1>
        <table class="table table-bordered mt-5">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Address</th>
                </tr>
            </thead>
            <tbody>
                @foreach($data as $key => $value)
                    <tr>
                        <td>{{ $value->id}}</td>
                        <td>{{ $value->name}}</td>
                        <td>{{ $value->address}}</td>
                    </tr>
                @endforeach
            </tbody>
        </table>

       {!! $data->links() !!}
</div>
    </body>
</html>

Adding Routes

In this step, we just need to define a route. For that make the following changes to the route file. Here, we have created /view-data route which will call the index method of DataController.

routes\web.php

<?php

use App\Http\Controllers\DataController; //import
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});
Route::get('/view-data', [DataController::class, 'index']); //add this line

Testing Our Application

php artisan serve

Open the below URL into your browser :

http://127.0.0.1:8000/view-data

In the output, it will display the name and address of 10 people and provides a link to the next and previous. When the user clicks on that link it works accordingly.