How to implement DataTables server-side in laravel
Initializing Yajra laravel-datatables plugin
We need to install yajra package using composer.
Run the following the command to install it,
composer require yajra/laravel-datatables-oracle:~6.0
or else add the following code to composer.json file and run composer install
"require": { .... .... "yajra/laravel-datatables-oracle": "~6.0" }
and add DataTables to providers list /config/app.php
'providers' => [ ..... ..... Yajra\Datatables\DatatablesServiceProvider::class,
],
and finally we publish the configuration,
php artisan vendor:publish --tag=datatables
View part ( showing the table )
Here we show all the data in a table, we use the same data from previous example,
<table class="datatable mdl-data-table dataTable" cellspacing="0" width="100%" role="grid" style="width: 100%;"> <thead> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Gender</th> <th>Country</th> <th>Salary</th> </tr> </thead> <tbody> </tbody> </table>
the class names used above for table are as suggested by datatables.net/examples/styling/material.html
DataTables js part
We use some java script to initialize DataTables, process server-side requests and for the material design part we use.
<script> $(document).ready(function() { $('.datatable').DataTable({ processing: true, serverSide: true, ajax: '{{ route(' serverSide ') }}', columnDefs: [{ targets: [0, 1, 2], className: 'mdl-data-table__cell--non-numeric' }] }); }); </script>
Function to retrieve data from database
As we see in the above script, the ajax call routes to serverSide, here is the logic for it,
Route::get('/serverSide', [ 'as' => 'serverSide', 'uses' => function () { $users = App\Data::all(); return Datatables::of($users)->make(); } ]);