How to implement datatables in Laravel

How to implement datatables in Laravel

Hello readers, I am back with another post to let you know how to implement datatables plugin in laravel. Datatables is a jQuery plugin for table extender, it provides the functionalities like search, sort, pagination on a table of information to handle the data more effectively. Earlier we implemented search, pagination, pagination on search results individually without using any plugins, here we will do it using datatables plugin.

There are also a similar table extender plugins like datatables and bootgrid is one of them, a post on implementing bootgrid is also available here.

Here we used the basic initialization of datatables, I made another post on implementing datatables server-side, I recommend you to have a look at it here.

You can also watch the video on YouTube here.

Working Demo      Project on Github

Step 1: Initializing datatables

Let’s include the required bootstrap, datatables js and CSS files along with jquery,

<script src="//code.jquery.com/jquery-1.12.3.js"></script>
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script
    src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet"
    href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet"
    href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">

We show the data in a table so let’s create the table we require,

<table class="table" id="table">
    <thead>
        <tr>
            <th class="text-center">#</th>
            <th class="text-center">First Name</th>
            <th class="text-center">Last Name</th>
            <th class="text-center">Email</th>
            <th class="text-center">Gender</th>
            <th class="text-center">Country</th>
            <th class="text-center">Salary ($)</th>
            <th class="text-center">Actions</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

Note that the table above has an id id="table" we use that id to initiate datatables,

<script>
  $(document).ready(function() {
    $('#table').DataTable();
} );
 </script>

Step 2: Fetching data from the database

We collect some fake data from mockaroo.com and store it in our database, the table consists of id, first_name, last_name, email, gender, country, and salary fields. The SQL file can be found here.

Now we set up the database connection details in /.env file or in /config/database.php with appropriate details. for reference post on a database set up look here.

Now we create a model file for accessing the data in the database, running the following command will create a model file with the given name at /app/Data.php.

php artisan make:model Data

place the following code in it,

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Data extends Model
{
    protected $table="datatables_data";
}

now our model is ready, we can now fetch the data from it and pass that data to the view created above,

So in routes/web.php file, place the following code to fetch all the data from the table,

Route::get ( '/', function () {
    $data = Data::all ();
    return view ( 'welcome' )->withData ( $data );
} );

Working Demo      Project on Github

Step 3: Showing the data

In the previous step, we pass a variable $data to the view, it contains all the data we needed, so the view file where we created a table, we show this data in those <td> elements.

edit the view file as follows,

<tbody>
@foreach($data as $item)
<tr class="item{{$item->id}}">
    <td>{{$item->id}}</td>
    <td>{{$item->first_name}}</td>
    <td>{{$item->last_name}}</td>
    <td>{{$item->email}}</td>
    <td>{{$item->gender}}</td>
    <td>{{$item->country}}</td>
    <td>{{$item->salary}}</td>
    <td><button class="edit-modal btn btn-info"
            data-info="{{$item->id}},{{$item->first_name}},{{$item->last_name}},{{$item->email}},{{$item->gender}},{{$item->country}},{{$item->salary}}">
            <span class="glyphicon glyphicon-edit"></span> Edit
        </button>
        <button class="delete-modal btn btn-danger"
            data-info="{{$item->id}},{{$item->first_name}},{{$item->last_name}},{{$item->email}},{{$item->gender}},{{$item->country}},{{$item->salary}}">
            <span class="glyphicon glyphicon-trash"></span> Delete
        </button></td>
</tr>
@endforeach
</tbody>

We looped the $data variable and displayed all the results in the table.

Datatables implementation in laravel - justlaravel.com
Datatables implementation in laravel – justlaravel.com

Step 4: Deleting and Editing (the laravel part)

As we see in the table the last column ‘Actions’ with edit and delete options.
We have two buttons for edit and delete when clicked on those a modal will pop up showing the details and asking us to edit and delete the details in that row.

We use only one modal for editing and deleting purpose, as we did in previous tutorial about ajax crud operations, almost the same code we use here too, but with some extra fields in the edit modal form.

Step 4.1: Edit Modal

So when the edit button in the action column is clicked, we will adjust the only modal with appropriate buttons and actions like the name of the button in the modal, content in the modal.

following is the code executed when the edit button is clicked,

    $(document).on('click', '.edit-modal', function() {
        $('#footer_action_button').text(" Update");
        $('#footer_action_button').addClass('glyphicon-check');
        $('#footer_action_button').removeClass('glyphicon-trash');
        $('.actionBtn').addClass('btn-success');
        $('.actionBtn').removeClass('btn-danger');
        $('.actionBtn').removeClass('delete');
        $('.actionBtn').addClass('edit');
        $('.modal-title').text('Edit');
        $('.deleteContent').hide();
        $('.form-horizontal').show();
        var stuff = $(this).data('info').split(',');
        fillmodalData(stuff)
        $('#myModal').modal('show');
    });

Here we used a function fillmodalData() function to get the details of that particular row, the button’s data attribute contains all the info about that row so we use this inf and set them in the modal,

function fillmodalData(details){
    $('#fid').val(details[0]);
    $('#fname').val(details[1]);
    $('#lname').val(details[2]);
    $('#email').val(details[3]);
    $('#gender').val(details[4]);
    $('#country').val(details[5]);
    $('#salary').val(details[6]);
}

After the modal is shown, we can edit the data, then the data is saved after passing all the validation rules.

    $('.modal-footer').on('click', '.edit', function() {
        $.ajax({
            type: 'post',
            url: '/editItem',
            data: {
                '_token': $('input[name=_token]').val(),
                'id': $("#fid").val(),
                'fname': $('#fname').val(),
                'lname': $('#lname').val(),
                'email': $('#email').val(),
                'gender': $('#gender').val(),
                'country': $('#country').val(),
                'salary': $('#salary').val()
            },
            success: function(data) {
                if (data.errors){
                    $('#myModal').modal('show');
                    if(data.errors.fname) {
                        $('.fname_error').removeClass('hidden');
                        $('.fname_error').text("First name can't be empty !");
                    }
                    if(data.errors.lname) {
                        $('.lname_error').removeClass('hidden');
                        $('.lname_error').text("Last name can't be empty !");
                    }
                    if(data.errors.email) {
                        $('.email_error').removeClass('hidden');
                        $('.email_error').text("Email must be a valid one !");
                    }
                    if(data.errors.country) {
                        $('.country_error').removeClass('hidden');
                        $('.country_error').text("Country must be a valid one !");
                    }
                    if(data.errors.salary) {
                        $('.salary_error').removeClass('hidden');
                        $('.salary_error').text("Salary must be a valid format ! (ex: #.##)");
                    }
                }
                 else {
                     
                     $('.error').addClass('hidden');
                $('.item' + data.id).replaceWith("<tr class='item" + data.id + "'><td>" +
                        data.id + "</td><td>" + data.first_name +
                        "</td><td>" + data.last_name + "</td><td>" + data.email + "</td><td>" +
                         data.gender + "</td><td>" + data.country + "</td><td>" + data.salary +
                          "</td><td><button class='edit-modal btn btn-info' data-info='" + data.id+","+data.first_name+","+data.last_name+","+data.email+","+data.gender+","+data.country+","+data.salary+"'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-info='" + data.id+","+data.first_name+","+data.last_name+","+data.email+","+data.gender+","+data.country+","+data.salary+"' ><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");

                 }}
        });
    });
Datatables implementation in laravel - justlaravel.com
Datatables implementation in laravel – justlaravel.com

Basically, when the update button is clicked, it is routed to ajax call /editdata, it checks for validations, throws errors if validator fails or it saves the data in the database. So in the success function of the ajax call first check for errors, if any we display them appropriately or replace the row with new data.

Edit action :

Route::post ( '/editItem', function (Request $request) {
    
    $rules = array (
            'fname' => 'required|alpha',
            'lname' => 'required|alpha',
            'email' => 'required|email',
            'gender' => 'required',
            'country' => 'required|regex:/^[\pL\s\-]+$/u',
            'salary' => 'required|regex:/^\d*(\.\d{2})?$/' 
    );
    $validator = Validator::make ( Input::all (), $rules );
    if ($validator->fails ())
        return Response::json ( array (             
                'errors' => $validator->getMessageBag ()->toArray () 
        ) );
    else {
        
        $data = Data::find ( $request->id );
        $data->first_name = ($request->fname);
        $data->last_name = ($request->lname);
        $data->email = ($request->email);
        $data->gender = ($request->gender);
        $data->country = ($request->country);
        $data->salary = ($request->salary);
        $data->save ();
        return response ()->json ( $data );
    }
} );
Datatables implementation in laravel - justlaravel.com
Datatables implementation in laravel – justlaravel.com
Datatables implementation in laravel - justlaravel.com
Datatables implementation in laravel – justlaravel.com

Step 4.2: Delete Modal

When the delete button in the actions column is clicked a modal pops up, asking for delete confirmation.

    $(document).on('click', '.delete-modal', function() {
        $('#footer_action_button').text(" Delete");
        $('#footer_action_button').removeClass('glyphicon-check');
        $('#footer_action_button').addClass('glyphicon-trash');
        $('.actionBtn').removeClass('btn-success');
        $('.actionBtn').addClass('btn-danger');
        $('.actionBtn').removeClass('edit');
        $('.actionBtn').addClass('delete');
        $('.modal-title').text('Delete');
        $('.deleteContent').show();
        $('.form-horizontal').hide();
        var stuff = $(this).data('info').split(',');
        $('.did').text(stuff[0]);
        $('.dname').html(stuff[1] +" "+stuff[2]);
        $('#myModal').modal('show');
    });

When delete is clicked in the modal it is routed to ajax call /deleteData, which deletes the data from the database and updates the view.

    $('.modal-footer').on('click', '.delete', function() {
        $.ajax({
            type: 'post',
            url: '/deleteItem',
            data: {
                '_token': $('input[name=_token]').val(),
                'id': $('.did').text()
            },
            success: function(data) {
                $('.item' + $('.did').text()).remove();
            }
        });
    });

Delete action :

Route::post ( '/deleteItem', function (Request $request) {
    Data::find ( $request->id )->delete ();
    return response ()->json ();
} );
Datatables implementation in laravel - justlaravel.com
Datatables implementation in laravel – justlaravel.com

 

Server-side implementation of datatables : https://justlaravel.com/implement-datatables-server-side-laravel/

 

Working Demo      Project on Github



43 thoughts on “How to implement datatables in Laravel”

  • 1
    SAB on September 1, 2016 Reply

    Instead foreach you can use json response (serverSide: true, and ajax: url/path/list.php)

  • 4
    manytostao on September 2, 2016 Reply

    Please, make a tutorial on how to use AJAX features of the datatable plugin with laravel on server-side.

  • 7
    edward lance lorilla on September 4, 2016 Reply

    thank

    • 8
      avinash on September 4, 2016 Reply

      Thanks for stopping by 🙂

      Subscribe to justlaravel.com so that you wont miss any posts.

  • 9
    Asad javed on September 6, 2016 Reply

    hello sir, im new in laravel and programming,i followed you tutorial , all thing are working but if i use restful controller what would be url for updating?
    $.ajax({
    type: ‘PUT’,
    url: ‘/restaurant’,
    data: {
    ‘_token’: $(‘input[name=_token]’).val(),
    ‘id’: $(“#fid”).val(),
    ‘address_id’: $(‘#address_id’).val(),
    ‘name’: $(‘#name’).val(),
    ‘description’: $(‘#description’).val(),
    ‘phone’: $(‘#phone’).val(),

    • 10
      avinash on September 6, 2016 Reply

      Hi Asad javed,

      If you use restful controller, only one route is required,

      Route::resource('/someName', 'testController');

      So while calling PUT https verb calls to update function in testController.

      By default, there are some actions called to some https verbs, for detailed information on restful resources refer https://laravel.com/docs/5.3/controllers#resource-controllers

      • 11
        Asad on September 6, 2016 Reply

        im doing same thing but ajax could not found url help me ,

        ERROR
        “NetworkError: 405 Method Not Allowed – http://localhost:8000/restaurant
        MethodNotAllowedHttpException in RouteCollection.php line 218:
        ——-
        $(‘.modal-footer’).on(‘click’, ‘.edit’, function() {
        $.ajax({
        type: ‘PUT’,
        url: ‘/restaurant’,
        data: {
        ‘_token’: $(‘input[name=_token]’).val(),
        ‘id’: $(“#fid”).val(),
        ‘address_id’: $(‘#address_id’).val(),
        ‘name’: $(‘#name’).val(),

        • 12
          avinash on September 6, 2016 Reply

          Is your route, Route::resource('/restaurant', 'MainController');
          and controller logic is,
          public function update(Request $req,$id) {
          $data = Table::find($id);
          $data->someField = $req->get('someValue');
          $data->save();
          return response ()->json ( $data );
          }

          as put https verb calls update function with some parameter(here in above snippet id).

  • 13
    asadjaved63 on September 7, 2016 Reply

    Thanks for reply i did it same many many time but same error,

    “NetworkError: 405 Method Not Allowed – http://localhost:8000/restaurant

    MethodNotAllowedHttpException in RouteCollection.php line 218:

    in RouteCollection.php line 218

    here is my text
    http://textuploader.com/5879i

    kindly see where im doing wrong thanks

    • 14
      avinash on September 7, 2016 Reply

      I think you should remove the / in the route, just restaurant will do it. Route::resource('restaurant', 'RestaurantController');

      Forget to mention this in my previous comment.

      • 15
        asadjaved63 on September 8, 2016 Reply

        i did it same many many time but no luck. every time give me same 405 method allow

        NetworkError: 405 Method Not Allowed

        check my code and tell me where im wrong
        http://textuploader.com/587uv

        • 16
          avinash on September 8, 2016 Reply

          In url call also pass id as PUT requires an id, try changing the ajax to,
          $(‘.modal-footer’).on(‘click’, ‘.edit’, function() {
          $.ajax({
          type: ‘PUT’,
          url: ‘/restaurant/id’,
          data: {

          There should be an id in the URI for PUT https verb

  • 17
    Perdev on September 22, 2016 Reply

    how you can make this same example with modals and server side mode, its possible? i have with modals but work on cliend side, how can i change with server side?..

  • 19
    Perdev on September 22, 2016 Reply

    i mean that i have this
    @include(‘admin.usuarios.crear’)

    Id
    Nombre
    Apellidos
    Usuario
    Correo
    Tipo
    Acción

    @foreach ($users as $user)

    {{ $user->id }}
    {{ $user->nombre }}
    {{ $user->apellidos }}
    {{ $user->usuario }}
    {{ $user->email }}

    @if($user->tipo ==”administrador”)
    {{ $user->tipo }}
    @else
    {{ $user->tipo }}
    @endif

    id}}” data-toggle=”modal”>
    @include(‘admin.usuarios.editar’)

    id )}}” class=”btn btn-danger eliminar”>

    @endforeach

    and the js

    $(document).ready(function(){
    $(‘.usuario’).DataTable({

    processing: true,

    ajax : ‘{!! url(‘admin/tabla-users’) !!}’,
    columns: [
    {data: ‘id’},
    { data: ‘nombre’, name: ‘nombre’},
    { data: ‘apellidos’, name: ‘apellidos’},
    { data: ‘usuario’,name:’usuario’},
    { data: ’email’, name: ’email’},
    { data: ‘tipo’, name: ‘tipo’},
    { data: ‘accion’,name:’accion’}

    ]
    });
    });

    public function getUsuarios(){

    return Datatables::of(User::all())

    ->addColumn(‘accion’, function ($user) {
    return ‘id}}” class=”btn btn-warning”>
    ‘;
    })

    ->make(true);

    }

    how can i show the modal with data-target=”#editarusuario{{$user->id}}” and afther this include the file @include(‘admin.usuarios.editar’) i add the column as the example but doestn work the include file as the blade view, how can i do that?.. thanks for your help.

  • 21
    Perdev on September 22, 2016 Reply

    id}}” data-toggle=”modal”>
    @include(‘admin.usuarios.editar’) i mean just the data-target and after include the file for launch the modal ..

  • 23
    Perdev on September 22, 2016 Reply

    ok understand and you have any idea how can i do it with server side as my reference.. becouse this works only with client side.

  • 24
    Alejandro Lopez on December 10, 2016 Reply

    Hello: good tutorial….. modal windows popup fine…. but Update and Delete action’s isn’t working; thank you on advance!

  • 27
    Raul Arguello on January 20, 2017 Reply

    Hi, great tutorial has helped me a lot, but I think there is a problem with
    $ (‘. Modal-footer’). On (‘click’, ‘.edit’, function () {
             $ .ajax ({
                 Type: ‘post’,
                 Url: ‘/ editItem’,

    I’ve removed “/” from ‘/ editItem’ to make it work.

    Now, what does not work for me are the validations, they give me the empty field message always … what could it be?

  • 28
    anbu on September 20, 2017 Reply

    When I delete the row, It works fine. After I sort the column it shows the data which I deleted early.

    Can you please show me the example?

    How to retrieve the data from server after deleting?

    I want to reload the Datatable after deleting.

  • 29
    Nida Akram on October 1, 2017 Reply

    Hey i used you code but i am having problem that is when i click edit button form opens but i cannot do anything on that form its like the form is blocked please help me

  • 30
    Marces on March 18, 2018 Reply

    The revalidation (repeated times) of the edit form leads to a bug that breaks the application, having to reload the page. Even in the demo. I guess the problem is in ajax-jquery, when the json response with the errors is received. Thank you all, but it was a waste of time -weeks- for me. I could not find the defect. Goodbye!

    • 31
      avinash on March 18, 2018 Reply

      Can you specify the exact bug, it is working fine in the demo here http://demos.justlaravel.com/how-to-implement-datatables-in-laravel

      • 32
        Marces on March 26, 2018 Reply

        It happens after clicking the “update” button with some data that does not pass the validation. Sometimes at the first failed validation, sometimes at the second, almost always at the third.

        I think the problem is in the view, on line 207, where the modal is (re)shown. As this answer says in stackoverflow and the comment of “DelightedD0D” in it.

        https://stackoverflow.com/a/34870788

        Maybe the glitch is also produced by the slowness of the server’s response to a failed validation (in my case, produced by homestead). Together with the javascript asynchrony.

        Anyway, I could not make it work.

        • 33
          avinash on March 26, 2018 Reply

          Hello, as you see the javascript code I have written. When the edit form is submitted, the ajax URL check for errors and if any errors then the modal appears again.

          The basic functionality is the modal closes after clicking the update button, as there are validation errors am reopening the modal again to show errors.

          • 34
            Marces on March 27, 2018

            I solved it by simply removing the class “fade” on the div where “myModal” is declared. I still have no idea why it happens. The only thing that occurs to me is that I am in a local and test environment and things go much slower than on a server like where the demo is. And that produces the glitch.

            I showed you that I am not the only person who has it, and even a person who pointed out that it was a conflict with the datatables and jquery. Just to keep in mind if someone with the same problem appears.

            Anyway, the code is excellent! Thank you very much for your help and for your contribution! And sorry for my poor English!

  • 35
    Rajyaguru Hardik on June 16, 2018 Reply

    here is also not about any for datatable plug in…. what is tutorial.. therefore no one visiting you.

    • 36
      avinash on June 17, 2018 Reply

      Step 1 : Initializing datatables
      That is the first step of the tutorial, check again, that is the part you need to go through to include the datatables

  • 37
    oliv on October 5, 2018 Reply

    god bless you loved it

    • 38
      avinash on October 5, 2018 Reply

      Glad it helped you 🙂

  • 39
    Ken Musembi on January 14, 2019 Reply

    hey, i keep getting this error
    ErrorException thrown with message “Undefined variable: data (View: C:\xampp\htdocs\golfclub\resources\views\welcome.blade.php)”

    The routing also doesn’t work

  • 40
    avinash on January 15, 2019 Reply

    Have you passed the variable `$data` in controller/routes?

  • 41

    i just view: Uncaught TypeError: $(…).DataTable is not a function, there is relation on version jQuery? I tried others versions and nocoflict.

  • 42
    Mohammad Ali Abdullah on October 13, 2019 Reply

    Help full comments, thanks

  • 43
    Mohd Syahid on December 19, 2019 Reply

    Please help me

    https://pastebin.com/ZcGcTz07

Leave a Reply