AppDividend
Latest Web Development Tutorials

How To Integrate Datatables API In Laravel 5.5

316

How To Integrate Datatables API In Laravel 5.5 Tutorial using Javascript Library is today’s leading topic. If we want to list the data from the database then sorting, searching and pagination is the basic functionality, we want to use. There is also one package available in the Laravel to use Datatables, but we will use JS to integrate into our tables.

How To Integrate Datatables API In Laravel 5.5

First, we will install the Laravel as well as Install the AdminLTE theme. If you do not know, how to integrate the admin template in Laravel, then check out my How To Integrate Admin Template Into Laravel 5.5.

Step 1: Install Laravel 5.5.

Type the following command.

composer create-project laravel/laravel laraveltemplate --prefer-dist

After installation, edit the .env file and setup the database. Now, define the route for the admin template.

Route::view('admin', 'home');

Now, we need to create one master template file, which is inherited by all of its child pages.

In the resources  >>  views folder, make one file called master.blade.php.

Step 2: Make a layout file called master.blade.php

In this file, we will include all the css and js files, which will be needed in all the pages.



Now, make one folder inside views directory, called partials. In that folder, we will put our header and sidebar files. Our master.blade.php file looks like this.

<!-- master.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}" />
    <link rel="stylesheet" href="{{asset('css/AdminLTE.min.css')}}" />
    <link rel="stylesheet" href="{{asset('css/skins/_all-skins.min.css')}}" />
    <link rel="stylesheet" href="{{asset('font-awesome/css/font-awesome.min.css')}}" />
    @yield('stylesheets')
</head>
<body class="hold-transition skin-blue sidebar-mini">
    <div class="wrapper">
        @include('partials.header')
        @include('partials.sidebar')
        @yield('content')
    </div>
    <script src="{{ asset('js/jquery/dist/jquery.min.js') }}"></script>
    <script src="{{ asset('js/bootstrap/dist/js/bootstrap.min.js') }}"></script>
    <script src="{{ asset('js/adminlte.min.js') }}"></script>
    @yield('scripts')
</body>
</html>

This file includes required CSS and JS that will run the theme smoothly throughout the project.

Our header.js file looks like this.

<!-- header.blade.php -->

<header class="main-header">
    <a href="" class="logo">
        <span class="logo-mini"><b>A</b>LT</span>
        <span class="logo-lg"><b>Admin</b>LTE</span>
    </a>
    <nav class="navbar navbar-static-top">
        <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button">
            <span class="sr-only">Toggle navigation</span>
        </a>
        <div class="navbar-custom-menu">
            <ul class="nav navbar-nav">
                <li class="dropdown user user-menu">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                        <img src="{{asset('img/user2-160x160.jpg')}}" class="user-image" alt="User Image" />
                        <span class="hidden-xs">AppDividend</span>
                    </a>
                    <ul class="dropdown-menu">
                    <!-- User image -->
                        <li class="user-header">
                            <img src="{{asset('img/user2-160x160.jpg')}}" class="img-circle" alt="User Image" />
                            <p>
                                AppDividend
                            </p>
                        </li>
                        <li class="user-footer">
                            <div class="pull-right">
                                <a href="" class="btn btn-default">Sign out</a>
                            </div>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </nav>
</header>

Also, sidebar.blade.php file looks like this.

<!-- sidebar.blade.php -->

<aside class="main-sidebar">
    <section class="sidebar">    
        <div class="user-panel">
            <div class="pull-left image">
                <img src="{{asset('img/user2-160x160.jpg')}}" class="img-circle" alt="User Image" />
            </div>
            <div class="pull-left info">
                <p>AppDividend</p>
            </div>
        </div>
        <ul class="sidebar-menu" data-widget="tree">
            <li class="treeview">
                <a href="#">
                    <i class="fa fa-dashboard"></i> <span>Categories</span>
                    <span class="pull-right-container">
                    <i class="fa fa-angle-left pull-right"></i>
                    </span>
                </a>
                <ul class="treeview-menu">
                    <li><a href=""><i class="fa fa-circle-o"></i>Add Category</a></li>
                    <li><a href=""><i class="fa fa-circle-o"></i>All Categories</a></li>
                </ul>
            </li> 
        </ul>
    </section>
</aside>

Now, if you have included the proper css and js files, then hit the following URL in the browser. http://localhost:8000/admin

Related Posts
1 of 12



Step 3: Make model, migration, and controller.

You will see the working admin panel. Now, we need to create one model and migration file to make the table.

php artisan make:model Item -m

Also, create one controller file.

php artisan make:controller ItemController

Now, enter the following schema into the migrations.

<?php

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

class CreateItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }

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

Next, migrate the tables into the database via the following command.

php artisan migrate

Now, create one seeder file, to seed the data into the database.

php artisan make:seeder ItemTableSeeder

We will use model factories to populate the database. So let’s define the schema for the ItemTableSeeder.

Go to the database >> factories  >> UserFactory.php and define one more factory.

<?php

use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(App\User::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Item::class, function (Faker $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'price' => $faker->randomDigit,
    ];
});

Create the factory. Go to the newly created ItemTableSeeder.php file.

<?php

use Illuminate\Database\Seeder;

class ItemTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Item::class, 100)->create();
    }
}

Now, go to the DatabaseSeeder.php file.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call(ItemTableSeeder::class);
    }
}

Run the following command in your terminal.

php artisan db:seed

It will create 100 rows in the table, and if you find an error in the terminal like class not found then, please hit the following command.

composer dump-autoload

Step 4: Create index() function.

We need to create the index function inside the ItemController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ItemController extends Controller
{
    public function index()
    {
        $items = \App\Item::all();

        return view('home', compact('items'));
    }
}

Your web.php file looks like this.


Route::get('admin', 'ItemController@index');
<!-- home.blade.php -->

@extends('master')

@section('content')
    <div class="content-wrapper">
        <section class="content-header">
            <h1>
                Dashboard
                <small>Control panel</small>
            </h1>
            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
                <li class="active">Dashboard</li>
            </ol>
        </section>
        <section class="content">
            <div class="row">
                <table id="pageTable" class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Price</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach ($items as $item)
                        <tr>
                            <td>
                                {{ $item->id }}
                            </td>
                            <td>
                                {{ $item->name }}
                            </td>
                            <td>
                                {{ $item->price }}
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </section>
    </div>
@endsection
@section('scripts')
    <script src="{{ asset('js/jquery.dataTables.min.js') }}"></script>
    <script src="{{ asset('js/jquery.dataTables.bootstrap.min.js') }}"></script>
    <script>
         jQuery(function($) {
        //initiate dataTables plugin
        var myTable = 
        $('#pageTable')
        //.wrap("<div class='dataTables_borderWrap' />")   //if you are applying horizontal scrolling (sScrollX)
        .DataTable( {
            bAutoWidth: false,
            "aoColumns": [
                null,
                null,
                null
            ],
            "aaSorting": [],
            
            
            //"bProcessing": true,
            //"bServerSide": true,
            //"sAjaxSource": "http://127.0.0.1/table.php"   ,
    
            //,
            //"sScrollY": "200px",
            //"bPaginate": false,
    
            //"sScrollX": "100%",
            //"sScrollXInner": "120%",
            //"bScrollCollapse": true,
            //Note: if you are applying horizontal scrolling (sScrollX) on a ".table-bordered"
            //you may want to wrap the table inside a "div.dataTables_borderWrap" element
    
            //"iDisplayLength": 50
    
    
                select: {
                    style: 'multi'
                }
            });
        });
    </script>
@endsection

Now, you can hit this URL: http://localhost:8000/admin

Laravel Datatables

 

Finally, our How To Integrate Datatables API In Laravel 5.5 Tutorial is over.

 

 

 

Leave A Reply

Your email address will not be published.