Laravel 12 : Create Interactive & Responsive Tables with Yajra DataTables.

Touseef Afridi
09 Jan 26

Laravel 12 : Create Interactive & Responsive Tables with Yajra DataTables.

In this tutorial, we will learn how to build fast, interactive, and fully responsive tables in Laravel 12 using Yajra DataTables, with server-side processing and smooth Bootstrap 5 integration for modern web apps.


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 12 application with Yajra DataTables for displaying dynamic user data in an interactive table. You’ll start by creating a fresh Laravel 12 project or using an existing one, install the Yajra DataTables package to integrate DataTables seamlessly, run migrations and generate fake data for testing, and create a controller to fetch and return user data in a format suitable for DataTables. The guide also covers setting up routes and updating the view to include necessary assets like Bootstrap, jQuery, and AJAX for a responsive table. Finally, you’ll test the setup by running the Laravel development server and accessing the table in your browser to interact with, sort, and paginate the data dynamically.

Step # 1 : Create a Fresh Laravel 12 Project.

You can either use an existing Laravel 12 application or create a fresh project from scratch. If you have the Laravel Installer installed globally, you can quickly set up a new project by running.
laravel new datatables
If you don’t have the Laravel Installer, you can achieve the same result using Composer, which directly scaffolds the framework without any interactive prompts.
composer create-project laravel/laravel --prefer-dist datatables
When creating the project with Composer, Laravel automatically sets up a minimal project structure. In comparison, using the Laravel Installer will guide you through a short configuration process. For this setup, consider the following choices.
  • Starter Kit: Select None to keep the project lightweight and focused purely on the Laravel framework.
  • Testing Framework: Choose Pest for a modern and developer-friendly testing experience.
  • Database: Select MySQL as your main database driver to store and manage application data.
  • Run Migrations: Confirm with Yes so Laravel executes the default migrations right away.
  • Frontend Dependencies: Choose Yes to have Laravel automatically install the required frontend packages.

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

Step # 2 : Navigate to Your Laravel 12 Project.

Once your project is set up, open a terminal (such as Git Bash) and navigate to your Laravel project’s root folder.
cd c:xampp/htdocs/datatables
This puts you in the project root so you can run Artisan commands and manage your Laravel 12 application.

Step # 3 : Install Yajra DataTables for Laravel 12.

Run the following command to install the Yajra DataTables package, which makes it easy to integrate DataTables with Laravel 12.
composer require yajra/laravel-datatables-oracle:"^12.0"
This installs the package along with all its dependencies, enabling you to quickly display and manage dynamic, server-side data in your application while providing a simple way to work with jQuery DataTables, including features like sorting, filtering, pagination, and server-side processing.

Step # 4 : Generate Fake Data Using Tinker.

Before we can see our table in action, we need some users in the database. Laravel makes this super easy with Tinker. Open it by running.
php artisan tinker
Then, generate sample users with just one line.
User::factory()->count(30)->create();
This will add 30 users to your database, giving you enough data to explore sorting, filtering, and pagination while testing.

Step # 5 : Create a UserController.

To display our users in a table, we need a controller that will pull the data from the database and prepare it for DataTables. We can create it with.
php artisan make:controller UserController
After creating the controller, update the UserController.php file in app/Http/Controllers with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Yajra\DataTables\Facades\DataTables;
use Carbon\Carbon;
class UserController extends Controller
{
    // Return welcome view
    public function index()
    {
        return view('welcome');
    }
    // Handle AJAX requests for DataTables
    public function getAllUsers(Request $request)
    {
        // Base query for users table
        $users = User::query();
        return DataTables::of($users)
        // Format created_at column
        ->editColumn('created_at', fn($user) => $user->created_at?->format('d-M-Y'))
        // Format updated_at column
        ->editColumn('updated_at', fn($user) => $user->updated_at?->format('d-M-Y'))
        // Return JSON response expected by DataTables
        ->make(true);
    }
}
The UserController manages fetching user data and displaying it in the DataTable. It has two methods, index(), which loads the main view with the table, and getAllUsers(), which retrieves users from the database, formats their created_at and updated_at dates, and returns the data in a format DataTables can use. With this in place, the server-side logic for dynamically showing user data is ready.

Step # 6 : Set Up Routes.

First, make sure to import the UserController at the top of your routes/web.php file.
use App\Http\Controllers\UserController;
Then, add these routes.
// Display the DataTable view
Route::get('/', [UserController::class, 'index']);
// Handle AJAX requests and provide user data
Route::post('/getAllUsers', [UserController::class, 'getAllUsers']);
The GET route (/) loads the page with the table, and the POST route (/getAllUsers) handles the AJAX request, fetching and returning the user data for the DataTable. With these routes in place, your controller and table are fully connected and ready to interact.

Step # 7 : Update the Welcome View to Display Users Table.

Update the welcome.blade.php file by replacing its existing content with a simple table layout. This view loads all required frontend dependencies such as Bootstrap, jQuery, AJAX, and DataTables using CDN links. These libraries help create a responsive table interface and allow data to be fetched asynchronously using AJAX.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 12 - Code Shotcut Yajra DataTables (Bootstrap 5)</title>
    <!-- CSRF token for AJAX requests -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- DataTables Bootstrap 5 CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.5/css/dataTables.bootstrap5.min.css">
    <!-- jQuery for DataTables -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <!-- Bootstrap 5 JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <!-- DataTables JS + Bootstrap 5 integration -->
    <script src="https://cdn.datatables.net/1.13.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.5/js/dataTables.bootstrap5.min.js"></script>
</head>
<body class="bg-light">
    <div class="container mt-5">
        <h3 class="mb-4 fw-bold text-dark text-center">Code Shotcut Datatables</h3>
        <div class="card shadow-sm">
            <!-- Card Header -->
            <div class="card-header py-3">
                <h6 class="mb-0 fw-bold text-primary">Users</h6>
            </div>
            <!-- Card Body -->
            <div class="card-body">
                <!-- Users DataTable -->
                <table class="table table-striped table-bordered w-100" id="users">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Created At</th>
                            <th>Updated At</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
    <script>
        // Add CSRF token to all jQuery AJAX requests
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $(document).ready(function () {
            // Initialize DataTable
            $('#users').DataTable({
                processing: true,
                serverSide: true,
                responsive: true,
                ajax: {
                    url: "{{ url('/getAllUsers') }}",
                    type: "POST",
                },
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'name', name: 'name' },
                    { data: 'created_at', name: 'created_at' },
                    { data: 'updated_at', name: 'updated_at' },
                ]
            });
        });
    </script>
</body>
</html>
At this stage, the welcome view is adjusted to display a dynamic users table with DataTables, allowing records to be fetched and rendered via AJAX.

Step # 8 : Test the Datatables Integration.

Now it’s time to verify everything is working correctly. Launch the Laravel development server using the following command.
php artisan serve
Once the server is running, open your browser and visit: 127.0.0.1:8000.



You should see the users table displayed on the page, allowing you to browse the data, sort columns in both ascending and descending order, search, and interact with the table as expected.

Conclusion

By following this guide, you’ve successfully integrated Yajra DataTables into your Laravel application to display user data in a responsive and interactive table. The application can now fetch records from the database while supporting features like sorting and pagination through DataTables, and you’ve learned how to configure routes, create a controller for handling AJAX requests, and update the view by including Bootstrap, jQuery, and DataTables assets. This approach offers an efficient and scalable way to manage large datasets in Laravel while enhancing overall performance and user interaction.
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