Create Datatables in Laravel 8 using Yajra Datatables Package

Datatables is an essential user interface element; they help your site visitors visualize the complex data with unbound ease. This tutorial gives you answers on how to create datatables in the Laravel 8 application using Yajra DataTables from the absolute beginning.

DataTable is a mechanism to display complex information to users; datatable is an HTML table, represents data in row and column format. It contains different UI elements such as a Search bar, Pagination, Filter; you can simultaneously scan the information no matter how complex it is. For this Laravel 8 datatables tutorial, we are using the Yajra Datatable package via the composer.

Yajra Datatable is jQuery based DataTables API for Laravel, which supports Laravel 4|5|6|7|8 versions flawlessly. Consequently, you can use the Yajra package to display the server-side data in Tabular form; also, we will show you Laravel 8 datatables AJAX example with Bootstrap using this plugin.

What we will cover in this Laravel 8 DataTables tutorial:

  • Create a Laravel application
  • Install and Implement Yajra DataTables in Laravel
  • Adding pagination
  • Implementing instant search in Laravel table

So without further ado, let us begin integrating DataTables in the Laravel 8 project:

Create Laravel Project

Run command to install new Laravel application:

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

Move inside the project:

cd laravel-datatables-example

Install Yajra Datatable Plugin

Run command to install Yajra Datatable package in Laravel 8 application:

composer require yajra/laravel-datatables-oracle

Open config/app.php file and register the required Yajra DataTable packages:

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

Run configuration; however, this step is entirely optional.

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

Database Setting

Add the code in the .env file to make the database ready in the Laravel application:

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

Model and Migrations

Create ‘Employee’ Model to define the logical structure and relationship of the data table.

php artisan make:model Employee -m

Get to newly created database/migrations/timestamp_create_employeess_table.php and place the following properties.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateEmployeesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('phone');            
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employees');
    }
}

Insert below code in app/Models/Employee.php.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

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

Run migration using the following command.

php artisan migrate

Add Records in Database

Place the below code in database/seeds/DatabaseSeeder.php to add the fake records in database.

<?php

use Illuminate\Database\Seeder;
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,
                'phone' => $faker->phoneNumber
            ]);
        }
    }
}

Run php artisan command to seed the records in database.

php artisan db:seed

Generate and Set Up Controller

Run command to create EmployeeController, this controller contains the logic to fetch and display the data for data table.

php artisan make:controller EmployeeController

Add code in app/Http/Controllers/EmployeeController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Employee;
use DataTables;

class EmployeeController extends Controller
{

    public function showTable()
    {
        return view('home');
    }


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

Create Route

Add the below code in routes/web.php file to instantiate the route.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeeController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('employees', [EmployeeController::class, 'showTable']);

Route::get('employees/list', [EmployeeController::class, 'index'])->name('employees.list');

Integrate Yajra Data Table in Laravel

This final section of the tutorial tells you to implement Yajra data tables in the Laravel application. You will also see sorting, paginating, and filtering in action with real-time data coming from the database. Head over to the resources/views folder and create a home.blade.php file and insert the below code in it.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel 8 Data Tables Demo</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdn.datatables.net/1.10.22/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.22/js/dataTables.bootstrap4.min.js"></script>    
</head>

<body class="antialiased mt-5">
    <div class="container">
        <h2 class="mb-3">Yajra Datatables in Laravel</h2>
        <table class="table datatable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</body>

<script type="text/javascript">
    $(function () {
        var table = $('.datatable').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('employees.list') }}",
            "method": "GET",
            columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'phone', name: 'phone'},
            {
                data: 'action', 
                name: 'action', 
                orderable: true, 
                searchable: true
            },
        ]          
        });

    });

</script>

</html>

First, import the jQuery data tables CSS using the CDN path, also define the data tables CSS with Bootstrap.

Create a Static HTML table to display data in Tabular format and inject the data coming from Controller.

Check Laravel 8 DataTables Example

Run the command to start the project.

php artisan serve

Open the below URL:

http://127.0.0.1:8000/employees

Create Datatables in Laravel 8 using Yajra Datatables Package

Summary

The Laravel data table tutorial is over, i hope you have found this tutorial useful, if you have any feedback then please share with us.

Download Code: https://github.com/remotestack377/LaravelDatatablesExample