Laravel-datatables: enchant your tables with ease

Today I want to offer you an overview of a package made for DataTables.net integration into Laravel: laravel-datatables. This package allows you to easily create server-side processed DataTables with most of its available functionality while only writing a few lines of code.

Laravel-datatables installation

1. composer.json
"yajra/laravel-datatables-oracle": "~6.0"
2. config/app.php
Yajra\Datatables\DatatablesServiceProvider::class,
Facade should be automatically registered. 3. publishing configuration
$ php artisan vendor:publish --tag=datatables

Some simple magic

As an example I'm going to use our default Users. Let's take a simple view with a table:
<!DOCTYPE html>
<head>
  <link href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet">
</head>
<body>
  <table class="datatable">
    <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Created at</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
  <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
  <script>
    $(document).ready(function(){
      $('.datatable').DataTable({
            processing: true,
            serverSide: true,
            ajax: '{{ route('users.serverSide') }}'
        });
    });
  </script>
</body>
And here is our logic to get the main table up and running: (*this code was written directly into routes.php and it is no different than controller code)
<?php

use Yajra\Datatables\Datatables;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/users/serverSide', [
    'as'   => 'users.serverSide',
    'uses' => function () {
        $users = App\User::select(['id', 'name', 'email', 'created_at']);

        return Datatables::of($users)->make();
    }
]);
After entering into the page we should see a fully working datatable. This package works great with Eloquent and even Query Builder or Collections. Both of them have a different availability of functions but the main ones are: As you can see, this package has a lot to offer and I couldn't write everything down here (please visit their official site below). Of course, it can't fit all of our needs but this is a really great package which is a must when working with datatables. Keep in mind that there are some requirements involved in this package:
  • PHP 5.5.9 or later.
  • Laravel 5.0 or later.
As always, don't forget to read the official documentation.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials