How to implement datatables in laravel

Hello readers, am back with another post to let you know how to implement datatables plugin in laravel. Datatables is 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 initialisation of datatables, i made another post on implementing datatables server side, i recommend you to have a look at it here.

Working Demo      Project on Github

Step 1 : Initializing datatables

Lets include the required bootstrap, datatables js and css files along with jquery,

We show the data in a table so lets create the table we require,

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

Step 2 : Fetching data from database

We collect some fake data from 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 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.

place the following code in it,

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,

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,

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

Datatables implementation in laravel –

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 edit button in action column  is clicked, we will adjust the only modal with appropriate buttons and actions like name of the button in the modal, content in the modal.

following is the code executed when edit button is clicked,

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,

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

Datatables implementation in laravel –

Basically when 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 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 :

Datatables implementation in laravel –
Datatables implementation in laravel –

Step 4.2 : Delete Modal

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

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.

Delete action :

Datatables implementation in laravel –


Server side implementation of datatables :


Working Demo      Project on Github

29 thoughts on “How to implement datatables in laravel”

  • 18
    SAB on September 1, 2016 Reply

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

  • 21
    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.

  • 24
    edward lance lorilla on September 4, 2016 Reply


    • 25
      avinash on September 4, 2016 Reply

      Thanks for stopping by 🙂

      Subscribe to so that you wont miss any posts.

  • 26
    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?
    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(),

    • 27
      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

      • 28
        Asad on September 6, 2016 Reply

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

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

        • 29
          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');
          return response ()->json ( $data );

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

  • 30
    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

    kindly see where im doing wrong thanks

    • 31
      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.

      • 32
        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

        • 33
          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() {
          type: ‘PUT’,
          url: ‘/restaurant/id’,
          data: {

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

  • 34
    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?..

  • 36
    Perdev on September 22, 2016 Reply

    i mean that i have this


    @foreach ($users as $user)

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

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

    id}}” data-toggle=”modal”>

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


    and the js


    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”>



    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.

    • 37
      avinash on September 22, 2016 Reply

      Did u try while returning return 'id.'" class="btn btn-xs btn-primary" data-target="someModal"> Edit';
      and then here,

  • 38
    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 ..

  • 40
    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.

  • 41
    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!

  • 44
    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?

  • 45
    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.

  • 46
    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

Leave a Reply