Are you tired of dealing with static, outdated HTML tables in your Laravel applications? What if you could transform those tables into dynamic, interactive components that not only display data beautifully but also offer advanced functionality like inline editing, searching, and sorting—all without reloading the page? If that sounds appealing, welcome to the world of Yajra DataTables, where your data management dreams become a reality. In this comprehensive guide, we’ll walk you through setting up Yajra DataTables in Laravel 11, empowering you to create feature-packed tables that your users will truly appreciate.
To start, let’s understand what makes DataTables so powerful. Essentially, it’s a robust jQuery plugin designed to enhance HTML tables with advanced interaction controls. When combined with Laravel and Yajra’s DataTables package, it seamlessly enables server-side processing, resulting in dynamic and responsive tables.
Now, before moving to the practical implementation, let’s know about the DataTables.
Introduction to DataTables
DataTables enhances your web applications by enabling features like:
- Pagination
- Search functionality
- Sorting
- Inline editing, etc.
In short, it’s ideal for projects requiring a seamless display and manipulation of data in tabular formats.
Why Yajra DataTables?
Yajra DataTables is a Laravel package that simplifies the integration of the powerful jQuery DataTables plugin into your project. It offers:
- Enhanced interactivity: Seamless pagination, searching, and sorting.
- Server-side processing: Efficiently handle large datasets without performance hiccups.
- Customization: Easily add action buttons for editing, deleting, or more.
Client-Side vs. Server-Side Processing
Client-Side Processing
In client-side mode, all data is loaded into the browser and processed there, making it suitable for smaller datasets.
Server-Side Processing
For large datasets, server-side processing is recommended. As a result, only the requested data is sent from the server, reducing load time and enhancing performance. Furthermore, the Yajra DataTables package simplifies server-side operations in Laravel, making it easier to implement and manage.
Therefore, we are going to implement the below features in this post. So, by the end of this tutorial, you will have a solid understanding of using and implementing the Yajra DataTables in Laravel 11.
Setting Up Yajra DataTables in Laravel 11
I am assuming you have a Laravel 11 project setup. Hence, I am not going to create it. I will quickly jump to the Yajra Datatable package installation.
So, let’s come to the terminal and hit the below installation command using composer.
composer require yajra/laravel-datatables-oracle
After installation, you don’t need to configure anything related to Yajra Datatables. Because after Laravel version 5.5+, this will take care of it automatically.
Recommended: From Laravel 10 to 11: Upgrading Your Project for Enhanced Performance
Model and Migration Setup
We will need to set up the model and migration to work on the data. So that we can apply Datatable over there. Laravel already comes up with a User model and it’s respective migration. Hence, I will be using this same for implementing the Yajra Datatbales in Laravel 11.
Firstly, let’s customize the users table migration so that, simply navigate to the database/migrations folder and there you will have the users table migration.
In the users table migration, I will add one more column as phone_number.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('phone_number')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};
After adding the above migration, let’s migrate the database using the below command.
php artisan migrate
Once it is done, let’s add the fillable property in the User model. Therefore, let’s navigate to the User model and add the below fillable properties.
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'phone_number',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
We are done with the model setup. Therefore, in the next step, you will have to insert some dummy records in the users table to have the Yajra datatable on this. So, we will be using the Factory and Laravel comes up with the UserFactory class by default.
Recommended: How to Create and Use Custom Classes in Laravel 11
Seed the Database Using Factory For Yajra DataTables in Laravel 11
Simply navigate to the database/factories/UserFactory.php. Thereafter, you will have to add the fake property for the phone number field that we have added.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'phone_number' => fake()->unique()->phoneNumber(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
Now, next, you will have to execute this factory class to seed the users table. Therefore, I will be using the REPL command line that is Tinker. So, switch back to the terminal again and hit the below command.
php artisan tinker
User::factory->count(20000)->create()
I have specified the 20000 records to be inserted in the Users table. However, you can create this according to your need.
Once the execution is completed, we will create a controller to write the functionality to fetch the users data over the table.
Create a Controller for Rendering Yajra DataTables in Laravel 11
In order to create the controller, let’s enter the below command in the terminal.
php artisan make:controller UserController
After creating the controller, let’s add the functionality to render the data. So, let’s add the below functionality.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Yajra\DataTables\Facades\DataTables;
class UserController extends Controller
{
public function index(Request $request) {
if ($request->ajax()) {
$users = User::query();
return DataTables::eloquent($users)
# Add Index Column
->addIndexColumn()
# Parsing Date Format for Created At Column
->addColumn('created_at', function($user) {
return Carbon::parse($user->created_at)->format('Y-m-d');
})
# Adding Action Column
->addColumn('action', function($user) {
return '
<button data-id="'.$user->id.'" class="btn btn-success btn-sm edit-user">Edit</button>
<button data-id="'.$user->id.'" class="btn btn-danger btn-sm delete-user">Delete</button>
';
})
->rawColumns(['action'])
->make(true);
}
return view('users');
}
}
After adding the controller functions, you will have to create a view for rendering data and applying the Yajra DataTable in Laravel 11. Therefore, this step is crucial to display the data in a user-friendly table format with dynamic features like pagination, searching, and sorting.
Create a View and Apply Yajra DataTables in Laravel 11
To begin, you need to create a Blade file with the name users.blade.php
. Once the view file is created, you can then proceed to add the below snippet to integrate the Yajra DataTables and display the data effectively.
<!doctype html>
<html lang="en">
<head>
<title>Datatable in Laravel 11</title>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<!-- Bootstrap CSS v5.2.1 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
{{-- Datatable CSS --}}
<link rel="stylesheet" href="https://cdn.datatables.net/2.1.8/css/dataTables.dataTables.css" />
<style>
table tr {
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container py-5">
<div class="card">
<div class="card-header">
<h5 class="card-title">Client-Side & Server Side Datatable in Laravel 11</h5>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped datatable table-dark">
<thead>
<tr>
<th>Sl.</th>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Created At</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
{{-- jQuery CDN --}}
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<!-- Bootstrap JavaScript Libraries -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
{{-- Datatable JS --}}
<script src="https://cdn.datatables.net/2.1.8/js/dataTables.js"></script>
<script type="text/javascript">
// Initializing Datatable
$(document).ready(function() {
const table = $('.datatable').DataTable({
serverSide: true,
processing: true,
ajax: {
url: '{{ route("users.index") }}'
},
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', searchable: false },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'phone_number', name: 'phone_number' },
{ data: 'created_at', name: 'created_at' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
]
});
});
</script>
</body>
</html>
Next, you will have to create a route for rendering this view.
Recommended: Laravel 11 Interface: How to Create and Implement it Effectively
Create Routes for Yajra DataTables in Laravel 11
In the web.php
, you will have to add the below routes in order to ensure proper routing functionality for the application. Specifically, these routes will map the necessary URL paths to their corresponding controller actions, enabling seamless access to the relevant pages or data.
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::controller(UserController::class)->group(function() {
Route::get('users', 'index')->name('users.index');
});
That’s it. Therefore you are ready to run the application and see the results.
Conclusion
Yajra DataTables in Laravel 11 unlocks the potential of dynamic and interactive tables, making it a game-changer for modern web applications. Whether you’re creating simple CRUD functionality or building complex, data-heavy applications, this integration gives developers powerful tools for managing and displaying data in an easy and efficient way.
One of the key features of Yajra DataTables is its ability to handle server side datatables smoothly. As a result, your tables can scale gracefully, and efficiently managing thousands or even millions of records without sacrificing speed or performance. Consequently, this ensures that even with large datasets, users experience a seamless and responsive interface. Moreover, by leveraging server-side processing, the system minimizes client-side load, allowing for faster page rendering and reduced memory usage. Therefore, whether you’re dealing with a small set of data or an extensive database, Yajra DataTables consistently provides optimal performance. Furthermore, its flexibility and ease of integration with other frameworks make it a powerful tool for building dynamic, data-driven applications.
But that’s not all. In addition to its scalability, it offers useful features like custom filters, multi-column sorting, pagination, and inline editing. These features don’t just add more options; rather, they improve how users interact with your application. For instance, custom filters make it easy for users to focus on specific data points, while multi-column sorting, in turn, helps them organize and understand data better. Consequently, these features enhance the overall user experience, making it more intuitive and efficient.
Leave a Reply