Back to Blog 7 min read

Use Yajra DataTables In Laravel - Simple Guide

In the daily dev requirement, we usually show data on the front end, and with Datatables it looks more interactive and smooth. In the same way, we ar...

In the daily dev requirement, we usually show data on the front end, and with Datatables it looks more interactive and smooth. In the same way, we are going to explore Yajra Datatables in the Laravel ecosystem and how we can use them.

Yajra Datatables is a package that makes it easy to create dynamic server-side data tables with ease. It can be an easy add-on for your next Laravel project.

If you are new to this concept don't worry, I'll explain everything that will help you to use this easily.

How To Install

In Laravel, this can be installed with the following command:

composer require yajra/laravel-datatables-oracle:"^10.3.1"

You can go to their Installation page where you can see all the requirements stuff, I don't want to repeat that.

For CSS and Javscript you will be using Jquery DataTables.

For configuration you can see the configuration section otherwise in the short do these steps after installation.

Step - 1
// config/app.php

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


Step - 2

php artisan vendor:publish --tag=datatables

Why Yajra Datatable

Practically, I will say that it has a lot of things that make it easier to use Datatables once you get comfortable with defining columns and all, you will see it makes life easier.

So, I'll list down all the concepts that I saw really provide value to the developer and not extra theoretical lines here.

  1. It has the ability to modify columns by building Eloquent queries in it. Let me show you a small example of my code.
 /**
     * Get the query source of dataTable.
     */
    public function query(ImportedAttendance $model): QueryBuilder
    {
        $request = $this->request();
        // Log::info('request in payroll: '. json_encode($request->all(['designation','employee_company_id','employee_id','department','month','year'])));
        $designation = $request->designation ?? '';
        $employeeCompany = $request->employee_company_id ?? '';
        // $employeeId = $request->employee_id ?? '';
        $department = $request->department ?? '';
        $month = $request->month ?? '';
        $year = $request->year ?? '';
        // return $model->newQuery()->with(['employeeDetails', 'employeeDetails.user']);
        $query = $model->newQuery();
        $query->whereHas('employeeDetails', function ($query) use ($designation, $employeeCompany, $department) {
            if ($designation !== 'all') {
                $query->where('designation_id', $designation);
            }

            if ($employeeCompany !== 'all') {
                $query->where('client_id', $employeeCompany);
            }

            // if ($employeeId !== 'all') {
            //     $query->where('employee_details.user_id', $employeeId);
            // }

            if ($department !== 'all') {
                $query->where('department_id', $department);
            }
        });
        $firstDayOfNextMonth = Carbon::createFromDate($year, $month, 1)->addMonth();
        $lastDayOfMonth = $firstDayOfNextMonth->subDay();
        $lastDayOfMonthString = $lastDayOfMonth->format('Y-m-d');
        $query->where('month', $lastDayOfMonthString)->with(['employeeDetails.user']);
        return $query;
    }

2. When we use query builder / Eloquent Models in it, It becomes more handy to show data on fronted instead of tackling all of these in the blade file.

3. it comes with an HTML builder, you can build the columns in it. In my point of view, it makes the blade much more clear because everything goes from the DataTable Class to our view file.

There are a lot of other things that you will understand when you use it.

Use Case Example - How to use Yajra Datatables

Now let's see how can you use this Datatable package practically in your Project.

So, the installation guide is already explained now. It provides an artisan command with which we can create a Datatable Class.

php artisan datatable:make Dummy #it will automatically add DataTable in the end of the name

I have already created a Datatable class let me take you there. It's a simple crud for companies Table.

  1. CompanyController -
  2. CompanyDataTable
  3. CompanyModel
  4. companies/index.blade.php

These are the above files I'm gonna use for this small Crud Operation.

I am assuming that you can create a model/controller.

DataTable Class

I'm assuming that you have created the Datatable class. Doesn't matter what the main thing is the concept should be clear in mind.

<?php

namespace App\DataTables;

use App\Models\EmployeeCompany;
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\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class EmployeeCompanyDataTable extends DataTable
{
    /**
     * Build the DataTable class.
     *
     * @param QueryBuilder $query Results from query() method.
     */
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addIndexColumn()
            ->addColumn('action', function ($row) {
                $action = '<div class="task_view">
                    <div class="dropdown">
                        <a class="task_view_more d-flex align-items-center justify-content-center dropdown-toggle" type="link"
                            id="dropdownMenuLink-" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <i class="icon-options-vertical icons"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuLink-" tabindex="0">';
                $action .= '<a class="dropdown-item openRightModal" href="' . route('company.edit', [$row['id']]) . '">
                                <i class="fa fa-edit mr-2"></i>
                                ' . trans('app.edit') . '
                            </a>';
                $action .= '<a class="dropdown-item delete-table-row" href="javascript:;" data-company-id="' . $row['id'] . '">
                                <i class="fa fa-trash mr-2"></i>
                                ' . trans('app.delete') . '
                            </a>';
                $action .= '</div>
                    </div>
                </div>';
                return $action;
            })
            ->setRowId('id')
            ->rawColumns(['action']);
    }

    /**
     * Get the query source of dataTable.
     */
    public function query(Company $model): QueryBuilder
    {
        return $model->newQuery();
    }

    /**
     * Optional method if you want to use the html builder.
     */
    public function html(): HtmlBuilder
    {
        return $this->builder()
            ->setTableId('company-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            //->dom('Bfrtip')
            ->orderBy(1)
            ->selectStyleSingle()
            ->buttons([
                // Button::make('create'),
                // Button::make('export'),
                // Button::make('print'),
                // Button::make('reset'),
                Button::make('reload')
            ]);
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::make('id'),
            Column::make('name'),
            Column::make('email'),
            Column::make('phone'),
            Column::make('website'),
            Column::make('gst_number'),
            Column::computed('action')
                ->exportable(false)
                ->printable(false)
                ->width(60)
                ->addClass('text-center'),
        ];
    }

    /**
     * Get the filename for export.
     */
    protected function filename(): string
    {
        return 'Company_' . date('YmdHis');
    }
}

Let's understand the above Datatable Class now. I have tried going a little deeper into the methods. So, I can explain but few things I don't know how to work under the hood. And also not important.

  1. Method dataTable() returns the query instance with the result and performs an action with we can use each data in rawColumns.
  2. There's a method called computed() which says that this column needs some extra modifications that we define in dataTable() method.
  3. In query() method we can build queries for our uses, Maybe you want to use relations between models and joins so, you need to define in the query() method and then you can access that in your dataTable() method.
  4. getColumns() You have Column::make('id'), a static method that makes () accept name of the field as in the table of the database.
  5. If you want to you can add a title to the make('this_name_can_be_defined_in_datatable_method')->title(custom_title__for_the_column)->data(field_name_as_in_table).

Things should be much more clear for now. In the next blog, I'll be explaining more about Yajra Tables.

Controller Class

Once you have created the controller go to the index method(). And use your DataTable Class.

public function index(CompanyDataTable $datatables)
    {
        $somedata = Somedata::all();
        return $datatables->render('employees-companies.index', compact('somedata'));
    }

compact() functions accept the string as a variable name. //output will be ['somedata' => $somedata]

If you want to send data to the view file, You can use the above way in render() method in the second parameter you can add whatever data you want.

render() method renders the view file with data that has been returned from dataTable.

View Implementation

In your view file, you can use it simply as mentioned below in the snippet.

 {!! $dataTable->table(['class' => 'table table-hover border-0 w-100']) !!}

Conclusion

I hope that it will help you understand the basic use cases of Yajra Datatables. You will understand more once you start using this in your own projects. Thanks.