Laravel 5.8 – Setup Yajra Datatable with AdminLTE [Step By Step]

implement-yajra datatable in adminlte laravel

Hello Friends, Today i will show you how to use datatable plugin with AdminLTE admin theme in laravel. DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table.

We all know that laravel is rapid and time saving framework because every required packages are available in laravel. For datatable, we can use yajrabox datatable package. Yajrabox is famous laravel datatable package which gives all basic functionality which we need in laravel.

Install and setup laravel AdminLTE package

Here i have already setup AdminLTE theme in laravel, so i am skipping AdminLTE installation part. Please take a look and setup AdminLTE theme step by step as described in tutorial.

PART-1 : Setup AdminLTE theme in Laravel with demo example

I assume that you have setup adminLTE theme with laravel and now we will moving to yajrabox datatable installation.

Install and setup yajra datatable package

Next, lets install laravel yajrabox package using below composer require command

composer require yajra/laravel-datatables-oracle:"~9.0"

Register provider and facade on your config/app.php file.

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

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

Publish DataTable Service provider[It’s optional].

php artisan vendor:publish --provider="Yajra\DataTables\DataTablesServiceProvider"

Create country model

Now lets create country migration using below command

php artisan make:migration create_countries_table

Open country migration file and add country_name and country_code fields shown as below.

<?php

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

class CreateCountriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('country_name');
            $table->string('country_code');
            $table->timestamps();
        });
    }

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

After that run migration artisan command

php artisan migrate

Above command will create countries table in database.

Now we need to add countries in the database countries table. Here is a countries.sql file. Run this countries sql queries in your database.

Create country model

Now lets create Country model. Country model file contains all database related logic.

php artisan make:model Country

Above command will create Country.php model file under app/ directory. If you want to move all model files under separate app/Models directory then please check this how to move all eloquent model files under models directory. Now open Country.php file and add fillable fields as shown below.

Related:  Simple Pagination Code In PHP With Example

app/Country.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'country_name', 'country_code'
    ];
}

Create country controller file

Next, we will create country controller to list all countries related logic. We also need one layout file to show countries list.

First lets create controller using below artisan command

php artisan make:controller Admin/CountryController

Above command will create CountryController.php file in app/Http/Controllers/Admin folder. Open CountryController.php file and add methods shown as below.

CountryController.php

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Country;
use DataTables;

class CountryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $countries = Country::all();
        return view('admin.country.list', ['countries' => $countries]);
    }

    /**
     * Get
     *
     */
    public function getList()
    {
        $countries = User::select(['id', 'country_name', 'country_code', 'created_at', 'updated_at']);
        return Datatables::of($countries)->make(true);
    }
}

Create layout file

Next we will create layout file list.blade.php in resources/views/country directory.  This layout file will show country list in datatable.

list.blade.php

@extends('adminlte::page')

@section('title', 'Countries | Lara Admin Yajra')

@section('content_header')
    <h1>Countries</h1>
@stop

@section('content')
  <div class="row">
    <div class="col-xs-12">
      <div class="box">
        <div class="box-header">
          @if(Session::has('message'))
            <p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
          @endif     
        </div>
        <div class="box-body">
          <table id="laravel_datatable" class="table table-bordered table-striped">
            <thead>
              <tr>
                <th>Id</th>
                <th>Country Name</th>
                <th>Country Code</th>
                <th>Created At</th>
                <th>Updated At</th>
              </tr>
            </thead>
          </table>
        </div>
      </div>
      <!-- /.box -->
    </div>
    <!-- /.col -->
  </div>
@stop

@section('js')
<script>
  $(document).ready( function () {
    $('#laravel_datatable').DataTable({
      processing: true,
      serverSide: true,
      ajax: "{{ url('user-list') }}",
      columns: [
        { data: 'id', name: 'id' },
        { data: 'country_name', name: 'country_name' },
        { data: 'country_code', name: 'country_code' },
        { data: 'created_at', name: 'created_at' },
        { data: 'updated_at', name: 'updated_at' }
      ]
    });
  });
</script>
@stop

Create route for country listing

Finally we will setup routes to access country list in routes/web.php route file. Open web.php route file and add below country routes.

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return redirect('login');
});

Auth::routes();

Route::group(['middleware' => 'auth'], function () {
    
    ...
    
    // Country
    Route::resource('/country', 'Admin\CountryController');
    Route::get('/country-list', 'Admin\[email protected]');
});

Add country in menu items

Next we will add country menu item in config/adminlte.php file.

Related:  CodeandTuts - A programming-blog

config/adminlte.php

'menu' => [
    'MAIN NAVIGATION',
    [
        'text'        => 'Dashboard',   // Menu item display name
        'url'         => 'dashboard',   // Route url
        'icon'        => 'file',
    ],
    [
        'text'        => 'Users',       // Menu item display name
        'url'         => 'user',        // Route url
        'icon'        => 'users',
    ],
    [
        'text'        => 'Countries',   // Menu item display name
        'url'         => 'country',     // Route url
        'icon'        => 'globe',
    ],
],

This will add country menu item at left sidebar.

Now start your laravel app server using below artisan command.

php artisan serve

Register and login admin theme and navigate http://127.0.0.1:8000/country url and you will see countries list shown as below image. You can sorting countries data using sorting icons shown in titles of table. You can search countries too.

laravel-yajra-datatable-in-adminlte

For your practice

Here in users list [You can check here http://127.0.0.1:8000/user], there is user list with simple AdminLTE datatable and does not contain ajax datatable. Please make it ajax datatable same as we used in countries list. Let me know if you have any questions regarding it.

Final Words

I hope that you may like this tutorial on how to setup datatable in laravel with AdminLTE theme. If you have any questions then let me know in comment box. I would like to help.

Please let me know how you like this tutorial in comment box. Thank you for your time to read this tutorial.

About Chintan Panchal

I am web developer having 4+ year of experience of web development. I have worked on codeigniter, symfony, laravel and wordpress.

View all posts by Chintan Panchal →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.