laravel

How to Implement DataTables Ajax with Laravel 5

Share this article

This is how it looks in my ContactsTableSeeder let say if I want to seed 500 dummy data.

/**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Contact::class, 500)->create();
    }

Normally I’ll create a single controller to manage DataTables Ajax sources. So here I create a controller named as DatatablesController.

php artisan make:controller DatatablesController

Inside the controller, use Yajra DataTables package to prepare the data. I’ll create a function to return all contacts as follows:

public function getAllContacts()
    {
        $contacts = Contact::query();
        return Datatables::eloquent($contacts)
            ->make(true);
    }

Make sure to register your route to DatatablesController so that you can call it wherever you need it. I’ll share more complex setting in due course.

Create a view page where you want to use the DataTables. Use selector to attached DataTables to your table as follows.




<table id="contact">
...
</table>




<!-- inside script tag -->
$(function () {
   $('#contact').DataTable({
       processing: true,
       serverSide: true,
       ajax: '{!! route('datatables.contacts') !!}',
       columns: [
           { data: 'name', name: 'name' },
           { data: 'email', name: 'email' },
           { data: 'phone', name: 'phone' },
       ]
   });
});
<!-- / script tag -->

Make sure you have included DataTables css and js file in your header and footer of the view file. So you are done for a basic DataTables Ajax with Laravel 5 application.

To be continued.

Leave a Reply

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