datatables

How to use Yajra Datatables in Laravel

Hello Geeks, I’ll show you an example of how to use Yajra datatables in Laravel. Here is an example of a Laravel Yajra datatable. This tutorial will walk you through a simple Yajra Datatables Laravel example. This article will provide you with a simple yajra/laravel-datatables Laravel example.

This example works with Laravel 6, Laravel 7, Laravel 8, and Laravel 9.

Yajra Datatables allows us to perform quick searches, pagination, ordering, sorting, and other functions. Datatables are jQuery plugins that allow you to add advanced interaction controls to the data in your HTML tables. Datatables also support ajax for data searching and retrieval. Using Datatables, you can provide a very quick layout for search and sorting. Datatables can also be used in your Laravel application.
In this example, we will use the default “users” table and add some dummy users to it with tinker before listing all users with yajra datatables. So, let’s get started by following the steps below.

Step 1: Install Laravel

This step is optional; however, if you haven’t already created the laravel app, you can use the following command:

composer create-project laravel/laravel example-app

Step 2: Install Yajra Datatables in Laravel

In this step, we’ll use the Composer package manager to install yajra datatable, so open a terminal and type the following command:

composer require yajra/laravel-datatables-oracle

Step 3: Add Dummy Users in Laravel

In this step, we will use Tinker Factory to create some dummy users. So, let’s make some dummy records with the following command:

php artisan tinker

User::factory()->count(20)->create()

Step 4: Create Controller

At this point, we should make a new controller called UserController. This controller will handle layout, data requests, and response, so include the following content in the controller file:

app/Http/Controllers/UserController.php

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use DataTables;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = User::select('*');
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
       
                            $btn = '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';
      
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
          
        return view('users');
    }
}

Step 5: Add Route

In this step, we’ll create a route for the datatables layout file and another for getting data. So, open your “routes/web.php” file and add the route below.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;

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

Step 6: Create Blade File

Finally, let’s create users.blade.php (resources/views/users.blade.php) for layout, where we’ll write design code and insert the following code:

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Yajra Datatables Tutorial - aboutthenerd.com</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.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.11.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
     
<div class="container">
    <h1>Laravel Yajra Datatables Tutorial - aboutthenerd.com</h1>
    <table class="table table-bordered data-table">
        <thead>
            <tr>
                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th width="100px">Action</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
     
</body>
     
<script type="text/javascript">
  $(function () {
      
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('users.index') }}",
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
      
  });
</script>
</html>

Run Laravel App:

After you have completed all of the necessary steps, type the following command and press enter to run the Laravel app:

php artisan serve

Now, Enter the following URL into your web browser and view the app output:

http://localhost:8000/users

Leave a Reply