Laravel 9 Datatables Example: Create Datatables in Laravel

This is a comprehensive tutorial on how to create datatables using Yajra datatable package in Laravel application.

This laravel datatables tutorial helps you understand the nitty-gritty of tabular data in laravel.

We would see how to align yajra datatables in laravel from scratch. We will create a laravel app from the beginning and integrate datatables in Laravel.

We will use bootstrap to build datatables in laravel and also see laravel datatables ajax example.

Datatables in Laravel Example

Datatables are the UI mechanism created to search, paginate, sort, and order the users’ data to scan. DataTables is a plug-in provided by the jQuery Javascript library.

It is a highly flexible yet powerful tool developed over the foundations of progressive enhancement that adds all of these advanced features to any HTML table.

Datatables plugin offers following features:

  • Pagination
  • Quick search
  • Responsive
  • Beautiful themes
  • Multi column ordering
  • Various extensions

Let’s get started.

Create Laravel Project

By using the composer package manager execute the command and install the project.

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

Move to the app root.

cd laravel-yajra-datatables-example 

Setting Up Yajra Datatable Package

The YajraDatatable is developed to handle the server-side data for DataTables. The whole mechanism works on jQuery and supported AJAX within the paradigm of Eloquent ORM, Fluent Query Builder, or Collection.

Install the Yajra DataTable package in Laravel.

composer require yajra/laravel-datatables-oracle

Next, register the required datatable service in providers and alias within the config/app.php.

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

Create Model and Run Migrations

Using the below command we will create a model.

php artisan make:model Employee -m

Add code in database/migrations/timestamp_create_employeess_table.php.

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('mobile');
        $table->timestamps();
    });
}

Define the following properties in app/Employee.php.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $fillable = [
        'name',
        'email',
        'mobile',
    ];    
}

We are all set, just run migration.

php artisan migrate

Generate Fake Data

In order to show the Laravel Datatables example, we must have some data in the backend. To fill this gap, we will create some dummy data, and Faker will help us complete this task.

Add the values in database/seeds/DatabaseSeeder.php.

<?php

use Illuminate\Database\Seeder;

// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

        $gender = $faker->randomElement(['male', 'female']);

    	foreach (range(1,150) as $index) {
            DB::table('employees')->insert([
                'name' => $faker->name($gender),
                'email' => $faker->email,
                'mobile' => $faker->mobile
            ]);
        }
    }
}

Here you are, execute command to create fake data:

php artisan db:seed

Create Controller

We need to create a EmployeeController and here we write the code to render records from the database.

php artisan make:controller EmployeeController

Place the code app/Http/Controllers/EmployeeController.php.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Employee;
use DataTables;

class EmployeeController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Employee::latest()->get();
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){
                    $btn = '<a href="javascript:void(0)" class="edit btn btn-primary">Edit</a> <a href="javascript:void(0)" class="delete btn btn-danger">Delete</a>';
                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
      
        return view('index');
    }
}

Create Route

Next, we need to set up a route, include code in routes/web.php.

Route::get('employees', [
    'uses' => 'EmployeeController@index',
    'as' => 'employee-list'
]);

Show Data in Datatables

This laravel datatables tutorial is going to take a turn which is almost near the destination. So, create a index.blade.php file, It will load the datatables in the laravel view.

We are creating table using Bootstrap UI framework, so import the Bootstrap CSS in the head section of the laravel template.

Add code in resources/views/index.blade.php.

<!DOCTYPE html>
<html>

<head>
    <title>Datatables in Laravel Tutorial</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css" rel="stylesheet">
</head>

<body>

    <div class="container">
        <h2>Laravel 8|7 Yajra Datatables Example</h2>
        <table class="table yajra-dt">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Mobile</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

</body>

<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.21/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"></script>

<script type="text/javascript">
    $(function () {
        var table = $('.yajra-dt').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('student-list') }}",
            columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex'
                },
                {
                    data: 'name',
                    name: 'name'
                },
                {
                    data: 'email',
                    name: 'email'
                },
                {
                    data: 'mobile',
                    name: 'mobile'
                },
                {
                    data: 'action',
                    name: 'action',
                    orderable: true,
                    searchable: true
                },
            ]
        });

    });
</script>

</html>

Start Laravel App

Execute command to test the app:

php artisan serve

You can check the app on the following URL:

http://127.0.0.1:8000/employees