How to add pagination using Yajra Datatables in Laravel 9

DataTables is a jQuery library for implementing pagination.

For adding AJAX pagination needs to write a long script that – count total records with and without filters, fetch records, initialize Array with data, and return the JSON array with required fields.

In Laravel, there is a Yajra DataTables package that makes this pagination process a little easier to implement.

How to add pagination using Yajra Datatables in Laravel 9


Contents

  1. Install Yajra package
  2. Update config/app.php and publish configuration
  3. Add Database configuration
  4. Create a Table
  5. Create Model
  6. Create Controller
  7. Create Route
  8. Create View
  9. Demo
  10. Conclusion

1. Install Yajra package

Run the following command to install the Yajra package –

composer require yajra/laravel-datatables-oracle:"^10.0"

2. Update config/app.php and publish configuration

Open config/app.php file.

Add Yajra\DataTables\DataTablesServiceProvider::class, in providers.

'providers' => [
   // ...
   Yajra\DataTables\DataTablesServiceProvider::class,
],

Add 'DataTables' => Yajra\DataTables\Facades\DataTables::class, in aliases.

'aliases' => Facade::defaultAliases()->merge([
   // ...
   'DataTables' => Yajra\DataTables\Facades\DataTables::class,
])

Publish configuration

php artisan vendor:publish --tag=datatables

3. Add Database configuration

Open .env file to update the database connection.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

4. Create a Table

  • Create a new table employees using migration.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->id();
       $table->string('emp_name',60);
       $table->string('email',80);
       $table->string('gender',20);
       $table->string('city',100);
       $table->smallInteger('status',2);
       $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created and I added some records to it.

5. Create Model

  • Create Employees Model.
php artisan make:model Employees
  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – emp_name, email, gender, city, and status using the $fillable property.

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
   use HasFactory;

   protected $fillable = [
      'emp_name','email','gender','city','status'
   ];
}

6. Create Controller

  • Create PagesController controller.
php artisan make:controller PagesController
  • Import Employees model.
  • Import DataTables.
  • Create 2 methods –
    • index() – Load index view.
    • getDataTableData() – Using this method return DataTable data.

Pass employees records to Datatables::of(), using addColumn() change status response from 0/1 to Active/Inactive. Call make() to generate DataTable data and return it.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;
use DataTables;
class PagesController extends Controller
{

    public function index(){
       return view('index');
    }

    public function getDataTableData(){

       $employees = Employees::select('*');

       return Datatables::of($employees)
            ->addIndexColumn()
            ->addColumn('status', function($row){

                if($row->status == 1){
                    return "Active";
                }else{
                    return "Inactive";
                }

            })
            ->make();
    }
}

7. Create Route

  • Open routes/web.php file.
  • Define 2 routes –
    • / – Load index view.
    • /getdatatabledata – GET type route to return DatatTable data.
<?php
use Illuminate\Support\Facades\Route; 
use App\Http\Controllers\PagesController; 

Route::get('/', [PagesController::class, 'index']); 
Route::get('/getdatatabledata', [PagesController::class, 'getDataTableData'])->name('getDataTableData');

8. Create View

Create index.blade.php file in view folder.

Create <table id='empTable'>.

Initialize DataTable on #empTable and set processing and serverSide to true, ajax URL to "{{ route('getDataTableData') }}".

Using column option specify key names that need to read from DataTable return response.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>How to add pagination using Yajra Datatables in Laravel 9</title>

   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"/>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css"/>

</head>
<body>
   <div class='container mt-5'>
      <table id='empTable' >
          <thead >
              <tr>
                 <td>Username</td>
                 <td>Name</td>
                 <td>Email</td>
                 <td>Gender</td>
                 <td>Status</td>
              </tr>
          </thead>
      </table>
   </div>

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
   <script type="text/javascript">

   $(document).ready(function(){

      // Initialize
      $('#empTable').DataTable({
          processing: true,
          serverSide: true,
          ajax: "{{ route('getDataTableData') }}",
          columns: [
              { data: 'emp_name' },
              { data: 'email' },
              { data: 'gender' },
              { data: 'city' },
              { data: 'status' },
          ]
      });
   });

   </script>
</body>
</html>

9. Demo

View Demo


10. Conclusion

If you are already using the default Laravel pagination then you can replace it with Yajra DataTables to add more functionality to it.

You can also this tutorial to know how to add edit delete button in Yajra DataTables.

If you found this tutorial helpful then don't forget to share.

Leave a Comment