Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Laravel

Implementing DataTables in Laravel 11

  • 28 Jun, 2024
  • Com 28
How to Implement DataTables in Laravel 11

To implement datatables in Laravel, use the “yajra/laravel-datatables-oracle” package.

The datatables are jQuery plugins that allow you to add advanced interaction controls to your HTML tables data, which is very useful in UI/UX.

Datatables also provides Ajax for data searching and filtering. It gives the functionalities like search, sort, and pagination on a table.

Here is the step-by-step guide:

Step 1: Install Laravel Project

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

The latest version is Laravel 11, so it will install Laravel 11 on your machine.

Step 2: Setup MySQL database

I created a new Database inside phpmyadmin called laratables like this:

Creating a new database

Now, configure this new database in the .env file.

//.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=8889
DB_DATABASE=laratables
DB_USERNAME=root
DB_PASSWORD=root

Now migrate the tables using this command:

php artisan migrate

Creating tables via migrations

Step 3: Install the yajra/laravel-datatables-oracle package

Let’s install the yajra/laravel-datatables-oracle package using the below command:

composer require yajra/laravel-datatables-oracle

Installing yajra/laravel-datatables-oracle package

You can see that Laravel Datatables is v11.0.0, the latest version compatible with Laravel 11.

Step 4: Add Datatables ServiceProvider

Inside bootstrap >> provider.php file, add the DataTablesServiceProvider like this:

<?php

// providers.php

return [
    App\Providers\AppServiceProvider::class,
    Yajra\DataTables\DataTablesServiceProvider::class,
];

Step 5: Generating dummy data

To display the data in datatables, we need some user data. We will use the Factory to generate dummy users.

Type the below command to open Tinker, which will interact with our laravel application.

php artisan tinker

Now, we will generate 100 fake users using this command:

\App\Models\User::factory()->count(100)->create();

If you execute the above command, you will see like this:

Creating 100 fakes users using tinker

If you go to the mysql database (phpmyadmin), investigate the users table, and you will see something like this:

users table in phpmyadmin

Step 6: Creating a controller and route

Let’s create a DisplayDataController.php using the below command:

php artisan make:controller DisplayDataController

Let’s register routes in routes  >>  web.php file.

<?php

// web.php

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

Route::get('/', function () {
    return view('welcome');
});


Route::get('create', [DisplayDataController::class, 'create']);
Route::get('index', [DisplayDataController::class, 'index']);

Here, we defined two routes: one for creating a view and another for an AJAX request to fetch the dummy users from the database and display them on the front end.

Go to the DisplayDataController.php file and write the code inside the create() and index() functions.

<?php

// DisplayController.php

namespace App\Http\Controllers;

use App\Models\User;
use Yajra\DataTables\DataTables;
use Illuminate\Http\JsonResponse;
use Illuminate\View\View;

class DisplayDataController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(): JsonResponse
    {
        $collection = User::query();

        return DataTables::of($collection)->make(true);
    }

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

First, we imported the necessary classes, such as DataTables and User model, at the top of the file.

Inside the index() function, we fetch all the users using the Eloquent model and return the data in JSON format.

So, when the Datatables sends an Ajax request to this function, it will return a JSON response.

Step 7: Create a view file.

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

<html lang="en">
<head>
    <title>Laravel DataTables Tutorial</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>Implementing DataTables in Laravel 11</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>

First, we used online CDNs for Bootstrap 3 CSS, JS, jQuery, dataTables.min.css, and dataTables.min.js files.

Here, I have done that when the page is loaded, we send an AJAX request from the DataTables API to the server to fetch the users’ data and display it on the table.

We will display the ID, name, and email columns.

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

Run the below command.

php artisan serve

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

If all of your configuration and code are fine, then you will see something like this in the view:

Implementation of DataTables in Laravel 11

Let’s sort the data based on the Name column:

Sorting in DataTables

We can also search the data within the Datatable like this:

Searching in DataTables

You can see that DataTables comes with built-in pagination, too:

Pagination in DataTables

That’s all! I hope this tutorial is helpful for you and that you will implement DataTables in your project.

Post Views: 2,554
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Format Float Values with Python
Creating CRUD Application in Laravel 11 with Vue 3

28 Comments

  1. Snehal Parmar

    April 19, 2018 at 12:12 am

    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,

    Reply
  2. Andrea

    May 28, 2018 at 10:17 am

    in DisplayDataController.php, add:

    use dataTables;
    use App\User;

    and it works!

    Reply
    1. oswaldo

      September 9, 2018 at 6:57 pm

      thanks

      Reply
  3. spinkalher

    August 5, 2018 at 2:29 pm

    Thanks its working

    Reply
  4. jhon

    November 5, 2018 at 6:50 am

    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

    Reply
    1. CFerrante

      November 8, 2018 at 4:54 pm

      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,

      Reply
  5. maha

    November 13, 2018 at 2:34 am

    Thank you so much
    it’s works fine

    Reply
  6. Abdullah

    December 3, 2018 at 6:17 am

    Thank you.

    Reply
  7. Lein

    January 10, 2019 at 7:08 am

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

    Reply
  8. Luis Bautista

    January 16, 2019 at 2:44 am

    @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

    Reply
  9. Ropali Munshi

    January 25, 2019 at 3:56 am

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

    Reply
  10. Gede Adi

    February 7, 2019 at 12:27 am

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

    Reply
  11. Hansraj Sagar

    May 27, 2019 at 9:18 am

    Hi Sir how can use Eloquent Relations in yajra datatable

    Reply
  12. axl

    June 19, 2019 at 4:45 am

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

    Reply
  13. maryam

    September 12, 2019 at 2:08 am

    thanks a lot…

    Reply
  14. Chintan Panchal

    December 9, 2019 at 12:55 pm

    Great tutorial as usual, Thanks for sharing it.

    Reply
  15. Kashan Baig

    July 28, 2020 at 1:34 pm

    It Works. Thanks

    Reply
  16. jalpa

    February 17, 2021 at 9:51 am

    Please help me yajra datatable using api

    Reply
  17. Amit

    October 28, 2022 at 5:18 pm

    $data = DoctorSubCategory::with([‘doctorCategory’])->get();
    // dd($data);
    //— Integrating This Collection Into Datatables
    return Datatables::of($data)
    ->addColumn(‘action’, function($data) {
    return view(‘admin.doctor.action-doctor-subcategory’,compact(‘data’));
    })
    ->toJson();

    Reply
  18. Alban

    February 15, 2024 at 10:12 pm

    I keep getting: Target class [DisplayDataController] does not exist.

    Reply
  19. Keane Fann

    March 14, 2024 at 9:40 am

    I tried installing in Laravel 11 with composer require yajra/laravel-datatables-oracle:”^11″ but it gave errors, unless I change the “minimum-stability” in composer.json to “dev”. Any updates?

    Reply

Leave a Reply Cancel reply

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

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend