Laravel JQuery DataTable Example

Datatable are very handy and useful system that you may ever want to use in your existing panel and want to give more feature to your client. In Laravel there a package available for datatable that can be a life save and once you start using you will never let it go. So lets talk about Laravel JQuery Datatable package build by yajrabox.

Laravel JQuery DataTable Example
Laravel JQuery DataTable Example

Before start i assume you know how to install and configure your laravel simple project. After create a new project and setup your demo database with some dummy users or your data.

Send a Mail With Laravel

Laravel JQuery DataTable Example

First of all we need to install laravel/ui package (if your laravel version is >= 7) then you need to use bootstrap ui for finish this you need to follow below commands in your project terminal.

PowerShellCopy
composer require laravel/ui --dev
php artisan ui bootstrap --auth

now you need to add datatables asset via npm or yarn.

PowerShellCopy
// for npm users

npm install --save datatables.net-bs4 datatables.net-buttons-bs4

// for yarn users

yarn add datatables.net-bs4 datatables.net-buttons-bs4

now you add these assets to app.scss and bootstrap.js file

resources/js/bootstrap.js

JavaScriptCopy
require('bootstrap');
require('datatables.net-bs4');
require('datatables.net-buttons-bs4');

resources/scss/app.scss

CSSCopy
// DataTables Assets
@import "~datatables.net-bs4/css/dataTables.bootstrap4.css";
@import "~datatables.net-buttons-bs4/css/buttons.bootstrap4.css";

after these all modification you need to compile assets. To complete this step you need to follow below commands in your project terminal

PowerShellCopy
// for npm users

npm run dev / watch / prod

// for yarn users

yarn dev / watch / prod

Now after this all you need to modify your master file that you extends in your blade files (eg. app.blade.php)

Master File Modification

You need to add some script file before closing </body> tags.

HTMLCopy
    <script src="{{ mix('js/app.js') }}"></script>
    <script src="{{ asset('vendor/datatables/buttons.server-side.js') }}"></script>
    @stack('scripts')

After this you need to make a controller. Here we just use UserController for getting users data. So first we make a controller and also a datatables so we need to run some commands

PowerShellCopy
php artisan make:controller UserController
php artisan datatables:make Users

After this we need to setup our controller and datatables.

PHPCopy
<?php 

namespace App\Http\Controllers;

use App\DataTables\UsersDataTable;

class UserController extends Controller
{
    public function index(UsersDataTable $dataTable)
    {
        return $dataTable->render('users.index');
    }
}

Now we need to modify UsersDataTable.php file to show our column to front page for example we have created a sample here.

PHPCopy
<?php

namespace App\DataTables;

use App\User;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class UsersDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->rawColumns(['action'])
            ->editColumn('created_at', function(User $user){
               return $user->created_at->format('d-m-Y');
            })
            ->addColumn('action',function(User $user){
                   return '<button>Action</button>';
                });
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\User $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(User $model)
    {
        return $model->newQuery();
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->setTableId('users-table')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('Bfrtip')
                    ->orderBy(1)
                    ->buttons(
                        Button::make('create'),
                        Button::make('export'),
                        Button::make('print'),
                        Button::make('reset'),
                        Button::make('reload')
                    );
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::computed('action')
                  ->exportable(false)
                  ->printable(false)
                  ->width(60)
                  ->addClass('text-center'),
            Column::make('id'),
            Column::make('name'),
            Column::make('email'),
            Column::make('created_at')
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'Users_' . date('Y-m-dHis');
    }
}

now we edit our users/index.blade.php file

resources/views/users/index.blade.php

PHPCopy
@extends('layouts.app')

@section('content')
    {{$dataTable->table()}}
@endsection

@push('scripts')
    {{$dataTable->scripts()}}
@endpush

Now we need to add route in our routes/web.php file

routes/web.php

PHPCopy
<?php 


Route::get('/users', 'UsersController@index')->name('users.index');

Before run you need to add some dummy data in your users table so to do that you can use seeder.

Now You run your project on your local.

Conclusion

So here we go now we can make our table more attractive and ourself more productive in minimum time thats why we are developers. 😂. So If you stuck anywhere just comment below and if you want to help your friend and developer just share it to him/her.

Leave a Reply

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