Hey there! If you're working with large datasets in Laravel 12, manually handling tables can be slow and inefficient. That’s where Yajra DataTables comes in! It makes handling and displaying data easy with AJAX-powered tables, sorting, searching, and pagination.
In this guide, I'll show you how to set up and use Yajra DataTables step by step.
Steps to Integrate Yajra DataTables in Laravel 12
if you haven't the installed laravel 12 then you can install laravel 12 using the following command.
laravel new laravel12-datatables
Run the following command to install Yajra DataTables via Composer:
composer require yajra/laravel-datatables-oracle
Create a new controller if you don’t have one:
php artisan make:controller UserController
Now, open app/Http/Controllers/UserController.php and modify it like this:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use DataTables;
class UserController extends Controller
{
public function index(Request $request)
{
if ($request->ajax()) {
$data = User::latest()->get();
return DataTables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
return '<a href="#" class="btn btn-sm btn-primary">Edit</a>';
})
->rawColumns(['action'])
->make(true);
}
return view('users.index');
}
}
In routes/web.php, define a route for the DataTable:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index'])->name('users.index');
Create a new Blade file in resources/views/users/index.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 12 Yajra DataTables</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
</head>
<body>
<h2>Laravel 12 Yajra DataTables Example</h2>
<table id="userTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
$(document).ready(function () {
$('#userTable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('users.index') }}",
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'action', name: 'action', orderable: false, searchable: false }
]
});
});
</script>
</body>
</html>
Now, migrate your database and run the Laravel server:
php artisan migrate
php artisan serve
You might also like: