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.
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:
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:
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.