Laravel 11 - Yajra Datatables

Touseef Afridi
18 Sep 24

Laravel 11 - Yajra Datatables

In this tutorial, we will explore how to implement Datatables in Laravel 11, which enhances data presentation by adding search, sorting, and pagination features.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through setting up a Laravel application with Yajra DataTables for displaying dynamic user data in an interactive table. You’ll begin by setting up a fresh Laravel project or using an existing one, followed by installing the Yajra DataTables package to integrate DataTables seamlessly. After running migrations and generating fake data for testing, you’ll create a controller to handle data retrieval and return it in a format suitable for DataTables. The guide covers the creation of routes and updating the view to include necessary assets like Bootstrap, jQuery, and AJAX to enable a responsive table view. Finally, you’ll test the setup by running the Laravel development server and accessing the table in your browser, where you can interact with the data, sort it, and view it dynamically.

Step # 1 : Set Up a New Laravel Project or Use an Existing One.

You can either start with an existing Laravel application or create a fresh one. If you have Laravel installed globally, you can quickly set up a new project by running.
laravel new datatables
Alternatively, if you prefer using Composer, execute this command.
composer create-project laravel/laravel --prefer-dist datatables
During the installation process, you will be prompted to make some selections.
  • Starter Kit: Choose None to install Laravel without any built-in authentication.
  • Testing Framework: Select Pest for a clean and expressive testing setup.
  • Database Driver: Pick MySQL as your database.
  • Run Migrations: Type no to skip running the default migrations and creating the necessary tables.

Once completed, you will have a fresh Laravel project named datatables, with Pest set up for testing, MySQL configured as the database, and the initial migrations skipped, giving you a clean and fully prepared Laravel environment..

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/datatables
This will allow you to execute Artisan commands and manage your Laravel project from the terminal.

Step # 3 : Install the Yajra Datatables package.

Run the following command to install the Yajra Datatables package, which provides easy integration of DataTables with Laravel.
composer require yajra/laravel-datatables-oracle:"^11.0"
This will install the package and its dependencies, allowing you to easily use DataTables to display and manage dynamic data within your Laravel application.

Step # 4 : Migrate the tables.

Run the migration command to apply the default migrations and create the necessary database tables.
php artisan migrate
This will set up the required tables in your database, ensuring that your Laravel application is ready to work with the data structures needed for your project.

Step # 5 : Generate Fake Data Using Tinker.

To quickly generate test users for your application, use Laravel's Tinker. Start by running the following command to open the Tinker shell.
php artisan tinker
Inside Tinker, run.
User::factory()->count(30)->create()
This will generate 30 fake user records in your database, allowing you to easily test your application's functionality with fake data.

Step # 6 : Create a Controller.

Generate a new controller by executing the following command.
php artisan make:controller UserController
After generating the controller, open the UserController.php file located in the app/Http/Controllers directory and update it with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Yajra\DataTables\DataTables;
use Carbon\Carbon;
class UserController extends Controller
{
    // Return a view
    public function index()
    {
        return view('welcome');
    }
    // Method to handle AJAX requests and return user data in DataTable format
    public function getAllUsers()
    {
        // Retrieve all users from the database
        $users = User::all();
        return Datatables::of($users)
            // Format 'created_at' column to 'd-M-Y'
            ->editColumn('created_at', function ($user) {
                return $user->created_at ? with(new Carbon($user->created_at))->format('d-M-Y') : '';
            })
            // Format 'updated_at' column to 'd-M-Y'
            ->editColumn('updated_at', function ($user) {
                return $user->updated_at ? with(new Carbon($user->updated_at))->format('d-M-Y') : '';
            })
            // Return DataTable response
            ->make(true);
    }
}
In this step, we created a UserController to manage the logic for fetching user data and displaying it in a DataTable format. The controller contains two methods index(), which returns the main view (e.g., welcome.blade.php) where the DataTable will be shown, and getAllUsers(), which handles the AJAX request, retrieves all users from the database, formats the created_at and updated_at columns to a readable date format, and returns the data in a DataTable response. This completes the server-side logic for dynamically fetching and displaying user data in the DataTable.

Step # 7 : Create & Update Routes.

First, import the UserController class at the top of your routes/web.php file.
use App\Http\Controllers\UserController;
Next, add the following routes.
// Route to display the users DataTable view
Route::get('/', [UserController::class, 'index']);
// Route to handle AJAX requests and return user data for the DataTable
Route::post('/getAllUsers', [UserController::class, 'getAllUsers']);
The GET route (/) loads the view to display the DataTable, while the POST route (/getAllUsers) handles AJAX requests and returns user data for the DataTable.

Step # 8 : Update view.

Replace the content of welcome.blade.php to create a basic table view that includes the necessary assets like Bootstrap, jQuery, AJAX, and DataTables CDN for a responsive and dynamic table display. This will set up the table structure and enable AJAX-based data loading.
<!DOCTYPE html>
<html>
<head>
    <title>Laravel Yajra Datatables - Code Shotcut</title>
</head>
<!-- CSRF token for secure form submissions -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<!-- Bootstrap 4 styles for page layout -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- DataTables Bootstrap 4 styling for the table -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.1.6/css/dataTables.bootstrap4.min.css">
<!-- jQuery for manipulating the DOM and handling AJAX requests -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<!-- DataTables core JavaScript for rendering dynamic tables -->
<script src="https://cdn.datatables.net/2.1.6/js/dataTables.js"></script>
<!-- Bootstrap 4 JavaScript for interactive elements -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<!-- DataTables JavaScript for integration with Bootstrap 4 -->
<script type="text/javascript" src="https://cdn.datatables.net/2.1.6/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">
                    <!-- DataTable structure where user data will be populated -->
                    <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>
</body>
<script type="text/javascript">
    // Setup for CSRF token in AJAX requests for security
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    })
    // Base URL
    baseUrl = {!! json_encode(url('/')) !!}
    $(document).ready(function() {
        // Initialize DataTable with server-side processing and AJAX call
        var table = $('#users').DataTable({
            processing: true, // Show a loading indicator while processing
            serverSide: true, // Enable server-side processing for large datasets
            responsive: true, // Make the table responsive for mobile devices
            autoWidth: true, // Automatically adjust column widths
            pageLength: 10, // Set the default number of rows per page
            order: [0, 'asc'], // Default order: ascending by first column (ID)
            "ajax": {
                'url': baseUrl + '/getAllUsers', // API endpoint to fetch user
                'type': 'POST',
                'datasrc': '',
                'data': {
                    '_token': $("meta[name='csrf-token']").attr('content') //
                },
            },
            // Specify columns based on the structure of the returned data
            columns: [
                {data: 'id', name: 'id'}, // User ID column
                {data: 'name', name: 'name'}, // User name column
                {data: 'created_at', name: 'created_at'}, // Created at timestamp column
                {data: 'updated_at', name: 'updated_at'}, // Updated at timestamp column
            ],
        });
    });
</script>
</html>
In this step, we updated the view to display a dynamic table using Bootstrap, jQuery, DataTables, and AJAX, allowing us to fetch and show user data in a responsive and interactive table.

Step # 9 : It's time to test.

Start the Laravel development server by running the command.
php artisan serve
Then, access the following URL: 127.0.0.1:8000.
You’ll now see the users table, where you can view the data, sort it in ascending or descending order, and interact with the content.


Conclusion

By following this guide, you’ve successfully integrated Yajra DataTables into your Laravel application for displaying user data in a dynamic, responsive table. Your application can now retrieve and display user data from the database, with sorting and pagination functionality enabled through DataTables. You’ve also learned how to set up routes, create a controller to handle AJAX requests, and update your view to incorporate Bootstrap, jQuery, and DataTables assets for a seamless user experience. This integration provides an efficient way to manage and display large datasets in a Laravel application, enhancing both performance and interactivity.
For more details, refer to the Yajra DataTables documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering