Laravel 11 Yajra Datatables example

              Yajra DataTables is a popular package for integrating the jQuery DataTables plugin with Laravel. It simplifies adding server-side processing to DataTables in your Laravel applications. This tutorial will guide you on how to integrate Yajra DataTables with Laravel 11.

Laravel 11 yajra datatables - Integration of Yajra DataTables with Laravel 11 : A Step-by-Step Tutorial

Table Of Content

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

2 Introduction

In this Laravel 11 Yajra Datatables example, we will install the yajra/laravel-datatables package via Composer. We will work with the default users table, populate it with dummy data using Tinker, and list all users using Yajra DataTables, enabling search, sort, and pagination features. Let's dive into the steps.

3 Create / Install a Laravel Project

3.1 Install Laravel Project

Ensure your system has Composer installed. Run the following command to create a new Laravel project:

composer create-project laravel/laravel laravel11-datatable-app

Then, navigate to your project directory:

cd laravel11-datatable-app

3.2 Configure MySql Database

In the .env file, define the database credentials:

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

4 Install Yajra DataTables

To integrate Yajra DataTables with Laravel 11, install the Yajra DataTables package via Composer:
    
        composer require yajra/laravel-datatables
   
Next, publish the package’s configuration and assets:
    
        php artisan vendor:publish --tag=datatables
   

5 Generate Dummy Users

Generate dummy user data using Tinker with this command:
    
        php artisan tinker
       User::factory()->count(100)->create()
   

6 Create Controller - UserController

Create a UserController to handle DataTable functionality:

php artisan make:controller UserController

In your controller, use the getUsers method to render the DataTable:

<?php
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use DataTables;
  
class UserController extends Controller
{
    public function index()
    {
           return view('users');
    }

    public function getUsers(Request $request)
    {
        if ($request->ajax()) {

            $data = User::query();

            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
       
                        $btn = '<a href="javascript:void(0)" data-id="'.$row->id.'" onclick="return alert(\'You Clicked Edit Button\')" class="edit btn btn-primary btn-sm">Edit<a>';
                        $btn .= '<a href="javascript:void(0)" data-id="'.$row->id.'" onclick="return alert(\'You Clicked Delete Button\')"  class="delete btn btn-danger btn-sm">Delete</a>';
  
      
                            return $btn;
                    })
                    ->addColumn('created_at', function($row)
                        {
                        $created_at = date("d F Y", strtotime($row->created_at));
                        return $created_at;
                        })
                    ->addColumn('updated_at', function($row)
                        {
                        $updated_at = date("d F Y", strtotime($row->updated_at));
                        return $updated_at;
                        })    
                    ->rawColumns(['action'])
                    ->setRowClass('{{ $id % 2 == 0 ? "alert-success" : "alert-default" }}')
                    ->make(true);
        }
          
        
    }
}
?>

7 Define a Route

In the routes/web.php file, define the following routes:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get('/', [UserController::class, 'index']);
Route::get('get-users', [UserController::class, 'getUsers'])->name('get.users');

8 Create Blade File

Create a Blade file resources/views/users.blade.php to display the DataTable:


   <!DOCTYPE html>
<html>
<head>
    <title>Integration of Yajra DataTables with Laravel 11 : A Step-by-Step Tutorial - getsamplecode.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
       
<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3">Integration of Yajra DataTables with Laravel 11 : A Step-by-Step Tutorial  - getsamplecode.com</h3>
        <div class="card-body">
            <table class="table table-bordered " id="data-table">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Created At</th>
                        <th>Updated At</th>       


                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>
       
</body>
       
<script type="text/javascript">
  $(function () {
        
    var table = $('#data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('get.users') }}",
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'created_at', name: 'created_at'},
            {data: 'updated_at', name: 'updated_at'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
        
  });
</script>
</html>

9 Folder Structure

Ensure the folder structure is correctly set up with controllers, views, and routes to maintain the app's organization.

10 Run Laravel Server to Test the App

To test the application, run the following artisan command:

php artisan serve

11 Conclusion

This Laravel 11 Yajra Datatables example tutorial has covered all the steps necessary to integrate Yajra DataTables with Laravel 11. You can now explore the powerful features of Yajra DataTables in your Laravel application.

Tags