Laravel 12 with DataTables: Complete Tutorial for Server-Side Processing

Author

Kritim Yantra

Apr 07, 2025

Laravel 12 with DataTables: Complete Tutorial for Server-Side Processing

Introduction

DataTables is a powerful jQuery plugin that adds advanced interaction controls to HTML tables. When combined with Laravel 12, you can create high-performance, server-side processed tables with features like:

  • Pagination
  • Instant search
  • Multi-column sorting
  • AJAX reloading
  • Export buttons (Excel, PDF, CSV)

This tutorial covers everything from basic setup to advanced implementations.


1. Setting Up Laravel 12 with DataTables

1.1 Install Required Packages

composer require yajra/laravel-datatables-oracle
npm install datatables.net datatables.net-bs5 jquery

1.2 Configure Providers (Laravel ≤ 11)

For Laravel 12, package auto-discovery works. For older versions, add to config/app.php:

'providers' => [
    Yajra\DataTables\DataTablesServiceProvider::class,
],
'aliases' => [
    'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]

1.3 Publish Configuration (Optional)

php artisan vendor:publish --tag=datatables

2. Basic Server-Side Implementation

2.1 Create Model and Migration

php artisan make:model Product -m
// Migration
Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->decimal('price', 8, 2);
    $table->integer('stock');
    $table->timestamps();
});

2.2 Generate Test Data

php artisan make:factory ProductFactory
// DatabaseSeeder.php
Product::factory()->count(500)->create();

3. Building the DataTable

3.1 Controller Setup

// ProductsController.php
use App\Models\Product;
use DataTables;

public function index()
{
    return view('products.index');
}

public function getProducts()
{
    $model = Product::query();
    
    return DataTables::eloquent($model)
        ->addColumn('action', function($product) {
            return '<a href="/products/'.$product->id.'/edit" class="btn btn-sm btn-primary">Edit</a>';
        })
        ->toJson();
}

3.2 Routes

Route::get('/products', [ProductsController::class, 'index']);
Route::get('/products/data', [ProductsController::class, 'getProducts'])->name('products.data');

4. Frontend Implementation

4.1 Blade Template

<!-- resources/views/products/index.blade.php -->
<table id="products-table" class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
            <th>Stock</th>
            <th>Created At</th>
            <th>Actions</th>
        </tr>
    </thead>
</table>

4.2 JavaScript Initialization

$(document).ready(function() {
    $('#products-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('products.data') }}",
        columns: [
            { data: 'id', name: 'id' },
            { data: 'name', name: 'name' },
            { data: 'price', name: 'price' },
            { data: 'stock', name: 'stock' },
            { 
                data: 'created_at', 
                name: 'created_at',
                render: function(data) {
                    return new Date(data).toLocaleDateString();
                }
            },
            { data: 'action', name: 'action', orderable: false, searchable: false }
        ]
    });
});

4.3 Include Required Assets

<!-- In your layout file -->
<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

5. Advanced Features

5.1 Adding Filters

// Add above DataTable initialization
$('#filter-name').on('keyup', function() {
    table.column(1).search(this.value).draw();
});

5.2 Export Buttons

dom: 'Bfrtip',
buttons: [
    'copy', 'csv', 'excel', 'pdf', 'print'
]

Include required JS:

<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>

5.3 Row Selection

select: {
    style: 'multi'
},

6. Performance Optimization

6.1 Selective Column Querying

return DataTables::eloquent($model)
    ->addColumn('action', '...')
    ->only(['id', 'name', 'price']) // Only select these columns
    ->toJson();

6.2 Disable Searching on Unneeded Columns

columns: [
    { data: 'id', searchable: false },
    // ...
]

6.3 Cache Frequent Queries

$products = Cache::remember('products.datatable', 60, function() {
    return Product::all();
});

7. Real-World Example: User Management System

7.1 Controller with Relationships

public function getUsers()
{
    $model = User::with('department');
    
    return DataTables::eloquent($model)
        ->addColumn('department_name', function(User $user) {
            return $user->department->name;
        })
        ->toJson();
}

7.2 Complex Where Conditions

return DataTables::eloquent($model)
    ->filter(function ($query) {
        if (request()->has('status')) {
            $query->where('status', request('status'));
        }
    });

Conclusion

You've now learned how to:
✅ Implement server-side DataTables in Laravel 12
✅ Optimize performance for large datasets
✅ Add advanced features like exports and filters
✅ Handle relationships and complex queries

📌 Need help? Drop your questions below! 👇

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts