DataTables plugin in Laravel application

By CodersDrive
22-Jun-2020
JQuery

DataTables JavaScript is a very useful plugin for web developers to make any HTML table to include the feature of pagination, sort and search for data. In this post we will see how to download and use it in any laravel application.

Step-1 Download DataTables Javascript using npm

There are several ways to download DataTables Javascript files. In our case we will download using npm, as it will have better version control for developers. Use the following commands one after another at your terminal to download required files.

npm install datatables.net
npm install datatables.net-bs4

First one will download the main js file and the second one will download DataTables Bootstrap 4 integration files. If you want more styling options otherthan Bootstrap please check here.

Step-2 Import DataTables in to public/js/app.js

Open the file app.js at resources/js/ and append the following two lines to it.

//DataTables.net
import "datatables.net/js/jquery.dataTables.js";
import "datatables.net-bs4/js/dataTables.bootstrap4.js";

Now run the following command on your terminal. This command will import the downloaded DataTables script files mentioned in above commands to your project main scaffolding file app.js at public/js/.

npm run dev

Now you can use DataTables javascript function in your application. Before that you need to copy the file dataTables.bootstrap4.css present at /node_modules/datatables.net-bs4/css/ to public/css/. Usage of this in Laravel application is explained in the below example.

Example: Display all Clients details with DataTables
Step-1 Create a Model and Migration

First create a Model Client and its migration using the following command.

php artisan make:model Client -m

This command will generate Client.php Model Class at app/ path and its migration file 2020_mm_dd_xxxxxx_create_clients_table.php at database/migrations/ path. This migration file has the table column names, you can edit this file and add our required columns as shown below.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateClientsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return  void
     */
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table->id();
            $table->string('firstName');
            $table->string('lastName');
            $table->string('email');
            $table->string('phoneNumber');
            $table->string('address');
            $table->string('city');
            $table->string('country');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return  void
     */
    public function down()
    {
        Schema::dropIfExists('clients');
    }
}

In this example we have added 7 fields to this migration file ('firstName', 'lastName', 'email', 'phoneNumber', 'address', 'city', 'country'). Now run the following command to create "clients" table in your MySQL DB.

php artisan migrate

Now you can verify the created clients table logging into your MySQL DB.

Step-2 Make Model fields fillable

As Laravel works on MVC (Model View Controller) type architecture, for security reasons when ever a Model is created by default all the fields are not allowed to add data through Controllers. To enable this we have to edit the created Model Client at app/ location and edit the code as shown below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $guarded = [];
}

In the code shown protected $guarded = []; means no Model fields are guarded, hence all the table coulmns can be updated through Controllers. If we want to protect some columns not to be allowed for add/update through Controllers you can add them under "$guarded" array like this protected $guarded = ['address'];.

There is also otherway to protect using protected $fillable = ['firstName','lastName'];. Which means only 'firstName', 'lastName' fields are allowed to add/update through Controller.

Now you can add clients data to this table or you can generate fake data for development purpose as per below link.

Step-3 Add Route to show all clients

Create a route and append the following code to web.php file at routes/ location.

Route::get('/all-clients', 'ClientController@display');

When this url is accessed display() function under ClientController will be called. So, you have to create this controller.

Step-4 Create Clients Controller

Now create a Controller to manage data access from clients table to your application using the following command.

php artisan make:controller ClientController

Open the file ClientController.php created at path app/Http/Controllers/ and add the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Client;

class ClientController extends Controller
{
    public function display()
    {
        $clients= Client::all();
        return view('all-clients', compact('clients'));
    }
}
Step-5 Create Show Clients Page

Now create a page all-clients.blade.php at resources/views/ and add the following code.

@extends('layouts.app')
@section('content')
<link href="{{ asset('css/dataTables.bootstrap4.css') }}" rel="stylesheet">
<?php $l=1; ?>
<div class="container text-center">
<h1 class="text-center">Laravel Datatables Demo</h1>
<table class="table table-bordered table-hover table-sm table-striped" id="myTable">
<thead><th>S.No</th><th>Client Name</th><th>Email</th><th>Phone.No</th><th>Address/Location</th></thead>

<tbody>
@foreach($clients as $client)
<tr>
<td>{{$l++}}</td>
<td>{{$client->firstName}} {{$client->lastName}}</td>
<td>{{$client->email}}</td>
<td>{{$client->phoneNumber}}</td>
<td>{{$client->address}},<br>{{$client->city}},<br>{{$client->country}}</td>
</tr>
@endforeach
</tbody>

</table>

</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready( function () {
    $('#myTable').DataTable();
} );
</script>
@endsection

Using Jquery we call the DataTables function on table with id myTable. You can see a demo of this page using below link.

Demo

JQuery Laravel Laravel 7

Search blog..!

Connect with us