How To Integrate Yajra Datatables With Laravel 8

This Laravel 8 tutorial help to implement yajra datatble with laravel8. Yajra is an awesome grid plugin for laravel which is based on jquery datatable. It’s easy to integrate with laravel compared to datatable.

DataTables is a jQuery JavaScript library plug-in. It’s a powerful tool that adds all of these advanced features to any HTML table, thanks to its progressive enhancement basis.

Yajra Datatable

yajra is a jQuery DataTables API for Laravel 6/7/8. This plugin handles server-side works of DataTables jQuery plugin through AJAX option by considering the Eloquent ORM, Fluent Query Builder or Collection.

The main features of Yajra Datatable:

  • Pagination
  • Instant search
  • Multi-column ordering
  • Use almost any data source
  • Easily theme-able
  • Wide variety of extensions
  • Mobile friendly

Video Tutorial

If you are more comfortable in watching a video that explains How To Integrate Yajra Datatables With Laravel 8, then you should watch this video tutorial.

How To Create laravel Listing Using Yajra

This Laravel 8 datatables tutorial helps us with the necessary methods for creating and displaying yajra datatables in Laravel 8. We’ll create employee module listing, sorting, searching with pagination.

Create Laravel application

Let’s create a laravel app using composer

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

move to the laravel-app:

cd laravel-app

Install Laravel Yajra

The following command helps you install the Yajra DataTable plugin in Laravel.

composer require yajra/laravel-datatables:^1.5

if you are working laravel below to 5.5 then you need to add service provider in providers and alias inside the config/app.php file.

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

Configure Model and Migrations

Now, we’ll run the below command to create a model, and it holds the schema of the database table.

php artisan make:model Employee -m

Open database/migrations/timestamp_create_employees_table.php file and add the given below code.

<?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->integer('age');
            $table->integer('salary');
            $table->timestamps();
        });
    }

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

Let’s Open app/Models/Employee.php and updated the $fillable array.

<?php

namespace App\Models;

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

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

Run migration using the following command.

php artisan migrate

Seeds Data

I am inserting data manually using sql script.

INSERT INTO `employees` (`id`, `name`, `salary`, `age`) VALUES
(1, 'Tiger Nixon', 320800, 61),
(2, 'Garrett Winters', 170750, 63),
(3, 'Ashton Cox', 86000, 66),
(4, 'Cedric Kelly', 433060, 22),
(5, 'Airi Satou', 162700, 33),
(6, 'Brielle Williamson', 372000, 61),
(7, 'Herrod Chandler', 137500, 59),
(8, 'Rhona Davidson', 327900, 55),
(9, 'Colleen Hurst', 205500, 39),
(10, 'Sonya Frost', 103600, 23),
(11, 'Jena Gaines', 90560, 30);

Create DataTable Controller

Create an EmpController that contains the fundamental functionality for handling data fetching and display requests from the database.

Create a controller using the below command.

php artisan make:controller EmpController

Open app/Http/Controllers/EmpController.php file and add the following code.

<?php

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

class EmpController extends Controller
{
    //
    public function index()
    {
        return view('listing');
    }

    public function getEmployees(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="edit btn btn-success btn-sm">Edit</a> 
                    <a href="javascript:void(0)" class="delete btn btn-danger btn-sm">Delete</a>';
                    return $actionBtn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
    }

}

Define Route

You need to create a route and display datatables template in the view for our laravel application.

Open routes/web.php and add the given code.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmpController;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
    return view('welcome');
});

Route::get('employee', [EmpController::class, 'index']);
Route::get('emp/listing', [EmpController::class, 'getEmployees'])->name('emp.listing');

Display Data with Blade Template

We’ll create a view and display listing data using a blade template.

Open resources/views/listing.blade.php file and place the following code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8|7 Datatables 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 mt-5">
    <h2 class="mb-4">Laravel Yajra Datatables Example</h2>
    <table class="table table-bordered yajra-datatable">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Age</th>
                <th>Salary</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-datatable').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('emp.listing') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'name', name: 'name'},
            {data: 'age', name: 'age'},
            {data: 'salary', name: 'salary'},
            {
                data: 'action', 
                name: 'action', 
                orderable: true, 
                searchable: true
            },
        ]
    });
    
  });
</script>
</html>

The DataTable() method is defined, and the AJAX request is fetching the data from the server and displays the name, age, and salary with the help of Yajra DataTable package.

We’ve also set the orderable and searchable properties to true, so you can easily search the data and write your program.

Run the following command and check on the browser.

php artisan serve

Open the below URL into the browser and check data:

http://127.0.0.1:8000/employee
yajra-laravel

3 thoughts on “How To Integrate Yajra Datatables With Laravel 8

  1. Hi

    i am getting Datatables is undefined even though use Datatables is defined in the controller
    return Datatables::of($data)

Leave a Reply

Your email address will not be published. Required fields are marked *