In this post we will discuss about the datatables on the laravel. We will use yajra/laravel-datatables-oracle package for the datatables. In this post, we are using laravel 5.7, yet you can use this case for Laravel 5.5+ version. It gives the functionalities like search, sort, pagination on a table. Mostly, when we have a large number of records and we have to locate the particular ones we will use the datatables.

Install Project

First of all, we need to create the laravel project. So, open the windows terminal and redirect to the destination folder to install the project. Run the following command to install.

laravel new laraveldatatables

The next thing you should do after installing the Laravel is set your application key to a random string. If you have installed the Laravel via Composer or the Laravel installer, this key has already been set for you. If the application key is not set, your user sessions and other encrypted data will not be secure! You can set the application key by running following command.

php artisan key:generate

Set Up Database

On browser open the localhost\phpmyadmin and create a new database with name laraveldatatables.

CREATE DATABASE laraveldatatables;

Open the project on editor. Go to app\Providers\AppServiceProvider.php  and inside the boot method set a default string length.

use Illuminate\Support\Facades\Schema;
 
 
public function boot()
{
    Schema::defaultStringLength(200);
}

Now go to the .env file and change the database credentials with the following:

DB_DATABASE=laraveldatatables
DB_USERNAME=root
DB_PASSWORD=null

I have set up a local database credentials.

Next, migrate the two tables provided by the Laravel. Move to your cmd and run the following command.

php artisan migrate

It will place the two tables in database.

  1. users
  2. password_resets

Install Yajra Package

Firstly we will install yajra/laravel-datatables package by writing the following command in cmd:

composer require yajra/laravel-datatables

Define provider and aliases

Open the file config/app.php, find the providers and add the following service provider

'providers' => [
    // ...
    Yajra\DataTables\DataTablesServiceProvider::class,
],

Open the file config/app.php, find aliases and add the following:

'aliases' => [
        // ...
        'DataTables' => Yajra\DataTables\Facades\DataTables::class,
    ]

After completing the above step, use the following command to publish configuration & assets:

php artisan vendor:publish --tag=datatables

Generating Dummy Data

We need to generate some dummy data for this example. So write the following command in cmd.

php artisan tinker

//In tinker run the following code                                                                                                                                       factory(App\User::class,100)->create();
Database View

Create Controller & Route

php artisan make:controller UserController

It will create a controller file with the name UserController.php.

We will register route in routes/web.php file.

Route::get('index', 'UserController@index');
Route::get('datatable','UserController@datatable')->name('datatable');

We will go to the app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers\Admin\Transaction;

use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use App\User;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('users.index');
    }
 
    public function datatable(){
        $data = User::all();
        return DataTables::of($data)->make(true);

    }
}

Create a view File

Create a directory users in the resources/views and inside the users directory create a file with the name index.blade.php.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>


</head>
<body>
<div class="container">
    <h2>Laravel Datatables Tutorial Example</h2>
    <table id="example1" class="table table-striped table-hover table-bordered dt-responsive nowrap dataTable" cellspacing="0" width="100%">
        <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        </thead>
    </table>
</div>
</body>
</html>

<script>
    $(function () {
        $('#example1').DataTable({
            processing:true,
            pagingType:"full_numbers",
            scrollY:true,
            scrollX:true,
            ajax:"{{ url('datatable') }}",
            order: [ [0, 'desc'] ],
            columns: [
                {data:'id', name:'id'},
                {data:'name', name:'name'},
                {data:'email', name:'email'},
            ]
        });
    });
</script>

Here, when the page is loaded, we send an AJAX request to the server and get the exact data that we need to display on the table. In our case, it is id, name, and email. It appends all the data to the #example1 id with searchingsorting, and pagination functionality.

CONCLUSION

In this article, I discussed how we can datatable in laravel. This is a simple example you can add your own design as per your requirement. If you wish to add to the discussion or would like to ask a question, leave a comment below.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *