Laravel Jquery Yajra DataTable Everything for Yajra 10.x with New changes

Categories - Laravel PHP Framework Tags - JavaScript Laravel   Maniruzzaman Akash   3 weeks ago   61   0

What is Laravel DataTable

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table. Laravel DataTable is a Laravel package to support that. It uses that JQuery library and makes a Good looking UI for big table with searching, sorting, pagination and many more.

** Documentation: ** https://yajrabox.com/docs/laravel-datatables/10.0

How to Install

Basic doc link - https://yajrabox.com/docs/laravel-datatables/10.0/installation

** Install Composer command - **

composer require yajra/laravel-datatables:^9.0

Inside config/app.php ’s providers array append this line -

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

**Publish the vendors - **

php artisan vendor:publish --tag=datatables

Quick start practical example -

Basic doc link - https://yajrabox.com/docs/laravel-datatables/10.0/quick-starter

Create UsersDataTable

Inside app\DataTables folder, create a file called UserDataTable.php and add these codes -

<?php

namespace App\DataTables;

use App\Models\User;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Services\DataTable;

class UserDataTable extends DataTable
{
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))->addIndexColumn()
            ->addColumn('action', function ($row) {
                $html = '<a class="btn-link text-info" href="' . route('users.edit', $row->id) . '"><i class="fa fa-pencil"></i></a>';
                return $html;
            })
            ->editColumn('created_at', function ($row) {
                return $row->updated_at->format('Y-m-d');
            })
            ->editColumn('updated_at', function ($row) {
                return $row->updated_at->diffForHumans();
            });
    }

    public function query(User $model): QueryBuilder
    {
        return $model->newQuery();
    }

    public function html(): HtmlBuilder
    {
        return $this->builder()
            ->setTableId('user-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->orderBy(1)
            ->selectStyleSingle()
            ->buttons([
                // Button::make('add'),
            ]);
    }

    public function getColumns(): array
    {
        return [
            Column::make('DT_RowIndex')->title('S/No')->orderable(false)->searchable(false),
            Column::make('name')->title('User Name'),
            Column::make('created_at')->title('Created'),
            Column::make('updated_at')->title('Last updated'),
            Column::computed('action')
                ->title('Action')
                ->exportable(false)
                ->printable(false)
                ->width(60)
                ->addClass('text-center')
        ];
    }

    protected function filename(): string
    {
        return 'User-' . date('YmdHis');
    }
}

Link this DataTable from the Controller -

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(UserDataTable $dataTable)
{
    return $dataTable->render('users.index');
}

Blade file to call this DataTable -

@extends('layouts.master')

@section('title')
    User List
@endsection

@section('admin-content')
    <div class="card card-body">
        {{ $dataTable->table() }}
    </div>
@endsection

@section('scripts')
    {{ $dataTable->scripts(attributes: ['type' => 'module']) }}
@endsection

Master Layout file if needs -

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>@yield('title', 'Admin Panel') | {{ config('app.name') }}</title>
    
    {{-- Datatable CSS --}}
    <link href="{{ asset('vendors/data-table/datatables.min.css') }}" rel="stylesheet">
    <link href="{{ asset('vendors/data-table/dataTables.bootstrap4.min.css') }}" rel="stylesheet">

    {{-- Custom styles --}}
    @yield('styles')
</head>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        @include('backend.partials.sidebar')
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                @include('backend.partials.navbar')
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <div class="container-fluid">

                    <!-- Page Heading -->
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">
                            @yield('title')
                        </h1>
                        @yield('page-right-side')
                    </div>

                    @yield('admin-content')

                </div>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            @include('backend.partials.footer')
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    
    {{-- Data table --}}
    <script src="{{ asset('vendors/jquery/jquery-3.6.0.min.js') }}"></script>
    <script src="{{ asset('vendors/data-table/datatables.min.js') }}"></script>
    <script src="{{ asset('vendors/data-table/dataTables.bootstrap4.min.js') }}"></script>

    <!-- Page level custom scripts -->
    @yield('scripts')

</body>

</html>

Hope, this will help you to generate a full datatable in Yajra DataTable 10.x.

** Tags: ** DataTable, laravel datatable, yajra datatable, laravel yajra, datatable 10.x, new datatable setup laravel, laravel datatable full setup

Previous
PHP If-else-elseif and Switch-case
Next
PHP String Functions - All necessary String functions in PHP to manage strings better.