Laravel 10 - Yajra Datatables
Laravel 10 - Yajra Datatables
In this tutorial, we will discuss how to integrate Yajra Datatables in Laravel 10 and explore its benefits for handling large datasets efficiently with dynamic table functionality.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
In this guide, we walk you through integrating Yajra DataTables into a Laravel 10 application from scratch. You’ll begin by setting up a new Laravel project and preparing frontend assets using Vite. After that, you’ll install the Yajra DataTables package, configure the database, and generate fake users using Laravel Tinker for testing. Then, you’ll create a controller to fetch and serve user data, define the necessary routes, and build a responsive frontend view powered by DataTables and Bootstrap 4. Finally, you’ll run the Laravel development server and test your fully functional DataTable, featuring real-time AJAX calls, pagination, sorting, and formatting, all rendered seamlessly in the browser.
Step # 1 : Start Fresh or Use an Existing Laravel 10 Project.
To get started, you can either use an existing Laravel 10 project or spin up a brand new one. If you're starting from scratch, it's always best to begin with a clean Laravel setup to avoid any leftover clutter or conflicts from previous work. If you have Laravel installed globally on your machine, you can quickly scaffold a new project using.
laravel new datatables
Alternatively, if you prefer using Composer (which is more common), you can run.
composer create-project laravel/laravel --prefer-dist datatables
This will create a fresh Laravel 10 project named datatables. Working in a clean environment not only simplifies debugging but also helps you focus on the functionality you're building perfect for testing new features like DataTables without unnecessary distractions.
Step # 2 : Open the Project and Set Up Frontend Assets.
Once your Laravel project is ready, the next step is to open your terminal (such as Git Bash or your preferred command-line tool) and navigate into the project folder. For example.
cd c:/xampp/htdocs/datatables
With the terminal inside your project directory, you'll want to install the frontend dependencies that Laravel uses to compile CSS, JavaScript, and other assets. Run the following command.
npm install && npm run dev
This will install all required packages and start the Vite development server, which handles live reloading and asset compilation. Keep this terminal running. Then, open a new terminal tab or window, navigate to the same project directory, and continue executing your Laravel-specific commands from there.
Step # 3 : Install Yajra DataTables Package.
Now that your project is set up, it's time to bring in the Yajra DataTables package, a powerful tool that simplifies working with dynamic and server-side DataTables in Laravel. To install it, run the following Composer command in your project’s root directory.
composer require yajra/laravel-datatables-oracle:"^10.3.1"
This command pulls in the Yajra DataTables package compatible with Laravel 10, allowing you to easily generate fast, paginated, and searchable tables directly from your Eloquent queries or database models. Once installed, you’ll be ready to configure and use DataTables in your application.
Step # 4 : Run Database Migrations.
With the Yajra DataTables package installed, the next step is to prepare your database tables. Laravel uses a migration system to define and version-control your schema changes easily. To run the default set of migrations (like users, password_resets, and others), execute the following command in your terminal.
php artisan migrate
Make sure your database is set up in the .env file. If it doesn’t exist, create it manually via phpMyAdmin or MySQL. Once done, run the migration to prepare the tables for use with Laravel and DataTables.
Step # 5 : Generate Fake Users with Tinker.
To test DataTables effectively, we need sample data. Use Laravel Tinker to create 30 fake user records.
php artisan tinker
User::factory()->count(30)->create()
This will populate your users table with dummy data, which we’ll later fetch and display in the DataTable.
Step # 6 : Create the User Controller.
Generate a new controller using the command below.
php artisan make:controller UserController
Now update the generated UserController.php with the following code to return a view and handle DataTables response.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Yajra\Datatables\Datatables;
use Carbon\Carbon;
class UserController extends Controller
{
// Render the main view
public function index()
{
return view('welcome');
}
// Fetch all users and return as DataTable
public function getAllUsers()
{
$users = User::all();
return Datatables::of($users)
->editColumn('created_at', function ($user) {
return $user->created_at ? Carbon::parse($user->created_at)->format('d-M-Y') : '';
})
->editColumn('updated_at', function ($user) {
return $user->updated_at ? Carbon::parse($user->updated_at)->format('d-M-Y') : '';
})
->make(true);
}
}
This controller includes two methods. One to load the main view and another to fetch all user records in a DataTables compatible JSON format.
Step # 7 : Define Routes.
To connect your controller to the browser, register the necessary routes in routes/web.php. First, import the controller at the top of the file.
use App\Http\Controllers\UserController;
Then, define the routes.
Route::get('/', [UserController::class, 'index']);
Route::post('/getAllUsers', [UserController::class, 'getAllUsers']);
The first route loads the main view, while the second handles the AJAX request to fetch user data for DataTables.
Step # 8 : Update Welcome View.
Now let's set up the front-end view to display user data using DataTables. Open resources/views/welcome.blade.php and replace its content with the following code.
<!DOCTYPE html>
<html>
<head>
<title>Laravel Yajra Datatables - Code Shotcut</title>
</head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<body>
<div class="container">
<div class="col-lg-12 mt-5">
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary custom-h6">Users</h6>
</div>
<div class="card-body table-responsive custom-card-body-0pad">
<table class="table table-striped table-bordered w-100" id="users">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Created At</th>
<th scope="col">Updated At</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$.ajaxSetup({
headers : {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
}
})
baseUrl = {!! json_encode(url('/')) !!}
$(document).ready(function(){
var table = $('#users').DataTable({
processing: true,
serverSide: true,
responsive: true,
autoWidth: true,
pageLength: 10,
order: [0, 'asc'],
"ajax" : {
'url' : baseUrl+'/getAllUsers',
'type' : 'POST',
'datasrc' : '',
'data' : {
'_token' : $("meta[name='csrf-token']").attr('content')
},
},
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'created_at', name: 'created_at'},
{data: 'updated_at', name: 'updated_at'},
],
});
});
</script>
</body>
</html>
This sets up a fully responsive DataTable that fetches user data via AJAX using the route you defined earlier. It utilizes server-side processing to efficiently handle large datasets and dynamically load user records from the backend. With built-in features like pagination, sorting, and searching, it provides a seamless and interactive way to manage and display data in a clean, user-friendly interface.
Step # 9 : It's Time to test.
Start the Laravel development server by running the following command.
php artisan serve
Once the server is up and running, open your browser and visit: http://127.0.0.1:8000. You should see the DataTable rendering user data fetched via AJAX. If everything is configured correctly, the table will display the list of users with proper pagination, sorting, and formatting.
Conclusion
By following this step-by-step guide, you’ve successfully integrated Yajra DataTables into a Laravel 10 application. Starting from a fresh Laravel setup, you installed and configured the DataTables package, generated fake user data for testing, and built a responsive interface that fetches data via AJAX with server-side processing. With sorting, pagination, and real-time updates, your application now features a dynamic and interactive user table powered by Eloquent and jQuery DataTables. This setup provides a solid foundation for managing large datasets efficiently in any Laravel project.
For more details, please refer to the Yajra DataTables documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments