Datatables Tutorial for Laravel 6

Introduction

In this tutorial, we will create data tables in Laravel 5 and 6 using Datatables package by yajra.

This package is created to handle server-side processing of DataTables jQuery Plugin via AJAX option by using Eloquent ORM, Fluent Query Builder or Collection.

Step 1. Installing Laravel

I'll quickly create and setup the laravel project for this tutorial. To install and setup the Laravel project in details. You can follow the below link.

Install and setup Laravel Project

To install the latest Laravel version enter the following command

composer create-project laravel/laravel datatables --prefer-dist

Step 2. Configuration

In this section, we will setup the database connection to interact with Mysql. By default laravel ships with .env.example file. Enter the following command to rename the file to .env

mv .env.example .env

Next, edit and configure the database details.

#.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=datatables
DB_USERNAME=root
DB_PASSWORD=root

My database name is datatables, the username and password is root. If you don't have any password for your mysql you can leave blank.

 

Step 3. Create model and migration

For this topic, I am going to use a category table for the demonstration. To create a category model and migration enter the following command.

php artisan make:model Category -m

The above command will create a category model and migration file.

Edit the migrations and replace the up function with the below code.

#database/migrations/2019_09_22_074642_create_categories_table.php

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('slug');
        $table->timestamps();
    });
}

Now enter the following command to migrate the category table.

php artisan migrate

Step 4. Create dummy data

I am going to use Laravel factory to insert dummy data. To do so create a factory class with the below command.

php artisan make:factory CategoryFactory

The above command will create factory class under database/factories directory. Edit the category factory class and add the below code.

#database/factories/CategoryFactory.php

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Category;
use Faker\Generator as Faker;

$factory->define(Category::class, function (Faker $faker) {
    return [
        'name' => $faker->sentence,
        'slug' => $faker->slug(6)
    ];
});
 

Step 5. Install Laravel datatables package

To install the datatables package enter the following command.

composer require yajra/laravel-datatables-oracle

Add Datatables Service Provider and Facade on config/app.php.

#config/app.php

'providers' => [
    ...
    Yajra\Datatables\DatatablesServiceProvider::class,
]
'aliases' => [
    ...
    'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]

Next, enter the following command to publish the config file.

php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"

The above command will publish configuration file under config/datatables.php

Step 6. Setting up view files

To setup view files we need to create a master file and include Datatables assets. Let's create our master blade.

#resources/views/layouts/master.blade.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel DataTables Tutorial - Desertebs</title>

        <!-- Bootstrap CSS -->
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
        <link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">

        <style>
            body {
                padding-top: 40px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            @yield('content')
        </div>

        <!-- jQuery -->
        <script src="//code.jquery.com/jquery.js"></script>
        <!-- DataTables -->
        <script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
        <!-- Bootstrap JavaScript -->
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <!-- App scripts -->
        @stack('scripts')
    </body>
</html>

Next, create a Datatables controller to write our logic

php artisan make:controller DatatablesController

Now Edit and paste the below code to the DatatablesController

#app/Http/Controllers/DatatablesController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Category;

class DatatablesController extends Controller
{
    public function index()
    {
        return view('index');
    }

    public function categoryData()
    {
        return Datatables::of(Category::query())->make(true);
    }
}
 

Now create an index view file under resouces/views to display the category data and paste the below code

#resources/views/index.blade.php

@extends('layouts.master')

@section('content')
    <table class="table table-bordered" id="category-table">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Slug</th>
                <th>Created At</th>
                <th>Updated At</th>
            </tr>
        </thead>
    </table>
@stop
@push('scripts')
<script>
$(function() {
    $('#category-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{!! route('datatables.category') !!}',
        columns: [
            { data: 'id', name: 'id' },
            { data: 'name', name: 'name' },
            { data: 'slug', name: 'slug' },
            { data: 'created_at', name: 'created_at' },
            { data: 'updated_at', name: 'updated_at' }
        ]
    });
});
</script>
@endpush

Setp 8. Setup routes

Now let's quickly add the routes.

#routes/web.php

Route::get('category', 'DatatablesController@index');
Route::get('get-category-data', 'DatatablesController@categoryData')->name('datatables.category');

Step 8. View in a web browser

Go to your application root directory and enter the below code to run the application

php artisan serve

and open http://127.0.0.1:8000/category. This URL will render the datatables as shown sample below. You can use search bar to filter column and click on the column name to sort ascending and descending order.

Laravel datatables preview data