How to Implement Yajra Datatables in Laravel 8

  12014 views   7 months ago Laravel

Datatable is jQuery plugin that provides responsive table and with rich features like automatic pagination, search, order with any column, export eo excel, csv etc. format.

yajra/laravel-datatables is a Laravel package which can imtegrate Datatable in Laravel application and render in the blade view. You can filter, customize fields from database.

yajra/datatable returns data in Json format, so you can also use yajra/datatable for api services. IN this article we will implement server side Datatable in Laravel 8. So let's get started.

1. Laravel project create

We are creating new project setup, so create new project using below command.

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

Now go to project directory

cd yajra

2. Install and configure package

Run the below command in your project to get the latest version of the datatable package.

composer require yajra/laravel-datatables-oracle

After that you need to register package classes in providers array in config/app.php file.

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

In the same file $aliases array, add the line.

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

3. Database migration

In the application environment .env file, change database details.

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

And run the migrate command.

php artisan migrate

4. Create dummy data

Now we need some dummy data to display. For that we will use Factory. First check your app/Models/User.php class use HasFactory trait.

Laravel already has factory class for User in /database/factories/ directory.

In the Terminal or CMD, open Laravel tinker using command.

php artisan tinker

And run the command to generate records. This will generate 100 dummy users.

User::factory()->count(100)->create();

5. Create route and Controller

Now in this step we are creating route for view in this path routes/web.php.

<?php

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

Route::get('users', [UserController::class, 'index'])->name('index');
Route::get('users/data', [UserController::class, 'data'])->name('data');

Now create controller using command:

php artisan make:controller UserController

Now open controller file at /app/Http/Controller/UserController.php file and create the above two methods.

<?php
     
namespace App\Http\Controllers;
     
use DataTables;
use App\Models\User;
use Illuminate\Http\Request;
     
class UserController extends Controller
{
    /**
     * users view
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        return view('users');
    }

    /**
     * data
     *
     * @return \Illuminate\Http\Response
     */
    public function data(Request $request)
    {
        $data = User::orderBy('id', 'desc')
            ->get();
        
        return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row) {
                       return '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';
                })
                ->rawColumns(['action'])
                ->make(true);
    }
}

6. Create view file

In the last step, we create blade view file at /resources/views/users.blade.php

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel Datatable example</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <link href="//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css" rel="stylesheet">
        <link href="//cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <h1 class="mb-3 text-center">Laravel Datatables Example </h1>
                <table class="table table-bordered datatable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th width="100px">Action</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            var table = $('.datatable').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('data') }}",
                columns: [
                    {data: 'DT_RowIndex', name: 'DT_RowIndex'},
                    {data: 'name', name: 'name'},
                    {data: 'email', name: 'email'},
                    {data: 'action', name: 'action', orderable: false, searchable: false},
                ]
            });
        });
        </script>
    </body>
</html>

Now everything is completed. Start the Laravel server using artisan command.

php artisan serve

In your web browser go to http://localhost:8000/users

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]