AppDividend
Latest Code Tutorials

Laravel 8 Datatables: How to Use Yajra Datatables In Laravel

Laravel Datatables provides us quick search, pagination, ordering, sorting in the table. The datatables are basically jQuery plugins that allow you to add advanced interaction controls to your HTML tables data which is very useful in UI/UX. Laravel Datatables also provide ajax for data searching and filtering.

Laravel Datatables

We use the yajra/laravel-datatables-oracle package for datatables.  In this tutorial, we use laravel, but you can use this example for the Laravel 5.1+ version. It gives the functionalities like search, sort, pagination on a table.

It is mainly used when we have millions of records, and we need to find the specific ones. I have written one tutorial on Datatables, which is on the client-side. It is how to integrate datatables api in laravel. So you can check it out.

First, we install the new Laravel Project.

Step 1: Install Laravel Project

We install the laravel project by typing the following command.

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

Step 2: Setup MySQL database

Now, configure this database in the .env file.

//.env

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

I have set up local database credentials.

Next, migrate two tables provided by Laravel Move to your cmd and hit the following command.

php artisan migrate

It will place two tables in your database.

  1. users 
  2. password_resets  

Step 3: Install yajra Package

First, we will install the yajra/laravel-datatables-oracle package by writing the following command in cmd.

composer require yajra/laravel-datatables-oracle

Step 4: Define providers and aliases.

Find the providers in config >> app.php file and register the DatatablesServiceProvider.

'providers' => [
        // ...
        Yajra\Datatables\DatatablesServiceProvider::class,
    ]

Place the aliases in config >> app.php file and register the aliases.

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

Step 5: Generating dummy data

We need to generate some dummy records for this example. So follow the command.

php artisan tinker

factory(App\User::class, 100)->create();

Laravel Datatables Tutorial

Step 6: Create a controller and route

php artisan make:controller DisplayDataController --resource

It will create one controller file called DisplayDataController.php.

We register routes in routes  >>  web.php file. So let us do it.

//web.php

Route::get('create', 'DisplayDataController@create');
Route::get('index', 'DisplayDataController@index');
//DisplayDataController.php

use Datatables;
use App\User;

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return Datatables::of(User::query())->make(true);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('displaydata');
    }

Step 7: Create a view file.

Create a file in the resources  >>  views  >>   displaydata.blade.php and put the following code in it.

//displaydata.blade.php

<html lang="en">
<head>
    <title>Laravel DataTables Tutorial Example</title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">  
        <link  href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
</head>
      <body>
         <div class="container">
               <h2>Laravel DataTables Tutorial Example</h2>
            <table class="table table-bordered" id="table">
               <thead>
                  <tr>
                     <th>Id</th>
                     <th>Name</th>
                     <th>Email</th>
                  </tr>
               </thead>
            </table>
         </div>
       <script>
         $(function() {
               $('#table').DataTable({
               processing: true,
               serverSide: true,
               ajax: '{{ url('index') }}',
               columns: [
                        { data: 'id', name: 'id' },
                        { data: 'name', name: 'name' },
                        { data: 'email', name: 'email' }
                     ]
            });
         });
         </script>
   </body>
</html>

Here, what we have done is, when the page is loaded, we send an AJAX request to the server and get the exact data we need to display on the table. In our case, it is id, name, and email. 

It appends all the data to the #table id with searching, sorting, and pagination functionality.

Next, run below command for a quick run:

php artisan serve

Open URL in your browser: http://localhost:8000/create

Possible Error:

DataTables warning: table id=table – Ajax error. For more information about this error, please see http://datatables.net/tn/7

Possible Solution: 

Change Providers and aliases in config >> app.php file

Yajra\Datatables\DatatablesServiceProvider::class,
'Datatables' => Yajra\Datatables\Datatables::class,

to this

yajra\Datatables\DatatablesServiceProvider::class,
'Datatables' => yajra\Datatables\Datatables::class,

Laravel Datatables Ajax

The below screenshot is captured when I have tried to search the tables, and it is working perfectly.

Laravel Datatables ExampleThat’s it for Laravel Datatables.

21 Comments
  1. Snehal Parmar says

    hey krunal,
    i did this tutorial but i got the above discussed error and i tried it by given solution but it doesn’t work…any other solution ??

    thank you,

  2. Andrea says

    in DisplayDataController.php, add:

    use dataTables;
    use App\User;

    and it works!

    1. oswaldo says

      thanks

  3. spinkalher says

    Thanks its working

  4. jhon says

    i got an error:
    DataTables warning: table id=table – Ajax error. For more information about this error, please see http://datatables.net/tn/7

    help me

    1. CFerrante says

      Did you see above, and try the steps?

      Possible Error:
      DataTables warning: table id=table – Ajax error. For more information about this error, please see http://datatables.net/tn/7

      Possible Solution:
      Change Providers and aliases in config >> app.php file

      Yajra\Datatables\DatatablesServiceProvider::class,
      ‘Datatables’ => Yajra\Datatables\Datatables::class,
      to this

      yajra\Datatables\DatatablesServiceProvider::class,
      ‘Datatables’ => yajra\Datatables\Datatables::class,

  5. maha says

    Thank you so much
    it’s works fine

  6. Abdullah says

    Thank you.

  7. Lein says

    hi sir i need to implement datatables in my project how can i handle

  8. Luis Bautista says

    @Jhon
    Verifica el orden de tus rutas, lo solucione de esta manera:
    Route::get(‘grupos/getdata’, ‘GrupoController@getdata’)->name(‘grupos.getdata’); // 1st
    Route::resource(‘grupos’, ‘GrupoController’); //Last

  9. lein says

    i cant get the datatables sir in my project please gave me a solution

  10. Ropali Munshi says

    How can we get the result of two tables by join in datatables?

  11. Gede Adi says

    How to add action button for laravel ? like edit delete or view ?

  12. Jonvent says

    DataTables warning: table id=table – Ajax error. For more information about this error, please see http://datatables.net/tn/7

    I change this:

    yajra\Datatables\DatatablesServiceProvider::class,
    ‘Datatables’ => yajra\Datatables\Datatables::class,

  13. Hansraj Sagar says

    Hi Sir how can use Eloquent Relations in yajra datatable

  14. axl says

    Nice Tuts. Where’s the next tutorial for edit and delete? Thank you.

  15. maryam says

    thanks a lot…

  16. Chintan Panchal says

    Great tutorial as usual, Thanks for sharing it.

  17. Kashan Baig says

    It Works. Thanks

    1. Krunal says

      Your welcome

  18. jalpa says

    Please help me yajra datatable using api

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.