Doing nothing for others is the undoing of ourselves. - Horace Mann
Some of the reasons are:
After package installation, don't forget to execute: php artisan vendor:publish --tag=datatables to publish the assets.
For datatables, these files will be published:
This tutorial is only applicable to Laravel v5.0 - v5.3. If you are using Laravel 5.4, please see upgrade guide.
php artisan datatables:make UsersDataTable
This will create a file: App\DataTables\UsersDataTable class with the following methods:
The default stub for ajax method is already usable and we can already leave this as is.
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->make(true);
}
We will also use the default stub for this method since we are dealing with User model.
public function query()
{
$users = User::select();
return $this->applyScopes($users);
}
We will add the columns that we want to display on our datatable. We will also include the buttons and display it in dom.
public function html()
{
return $this->builder()
->columns([
'id',
'name',
'email',
'created_at',
'updated_at',
])
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['csv', 'excel', 'pdf', 'print', 'reset', 'reload'],
]);
}
php artisan make:controller UsersController --plain
We will add the index method and inject our UsersDataTable class. Afterwards, we will render our view using our service.
namespace App\Http\Controllers;
use App\DataTables\UsersDataTable;
use App\Http\Requests;
class UsersController extends Controller
{
public function index(UsersDataTable $dataTable)
{
return $dataTable->render('users');
}
}
Create a file on resources/views/users.blade.php
Note: buttons.server-side.js is included in the package.
@extends('app')
@section('content')
{!! $dataTable->table() !!}
@endsection
@push('scripts')
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css">
<script src="https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js"></script>
<script src="/vendor/datatables/buttons.server-side.js"></script>
{!! $dataTable->scripts() !!}
@endpush
Route::resource('users', 'UsersController');