Laravel & DataTable - Installation

JC Tan avatar

JC Tan

  1. Setting up DataTable in Laravel
  2. Passing Data
  3. Filtering / Ordering
  4. Export to CSV, Excel or PDF

Information are being shown everywhere in tabular form, the normal HTML table is not enough in this data-driven era to just show data out right, most of the time we would need to paginate, search, sort and perform various actions to the data.

This is where DataTable shines.

DataTable is open source and out of the box it supports pagination, instant search, multi-column ordering, ajax data source and it's easily theme-able and has a variety of extensions if you need more funtionalities.

In this post, I will show you how to install DataTable using Laravel. It will be based on Laravel 5.7, but it should be the same across all the Laravel 5.x version which uses Laravel Mix.


Installation DataTable via NPM

After you've done setting up Laravel, install DataTable via npm.

npm install --save datatables.net-bs4
//npm install --save datatables.net-bs3 <-- if you are using bootstrap 3

Laravel ships by default with Bootstrap 4 which is what we will be using as a styling default for DataTable.

DataTable also provides styling support for various CSS framework e.g. Boostrap 3, Foundation, jQuery UI and Semantic UI.


Dealing with webpack.mix.js

We will need 2 files from DataTable to be compiled by Laravel Mix.

This is the default webpack.mix.js that ships with Laravel. We will include the javascript file into resources/js/bootstrap.js and css file into resources/sass/app.scss.

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

Include it in resources/js/bootstrap.js

require('datatables.net-bs4');

Include in resources/sass/app.scss

@import '~datatables.net-bs4/css/dataTables.bootstrap4.css';

Run npm run dev in your terminal to compile the necessary files.

Now we have the DataTable package compiled into both app.js and app.css which you be found in your public folder.

The last part is to call the .DataTable() function.

<script>
$(document).ready(function () {
  $('table').DataTable();
});
 </script>

End Result

Your original table now has the super power of pagination and instant search!

DataTable Enabled
DataTable Enabled

Sample blade file with data can be found here:
https://gist.github.com/omegachien/7d001bc3b7d853afed006dbb1203ca39

JC Tan avatar
Written By

JC Tan

Published in PHP
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.