DEV Community

Cover image for YajraBox Laravel DataTables: Building a Tags Management System
Asfia Aiman
Asfia Aiman

Posted on

YajraBox Laravel DataTables: Building a Tags Management System

DataTables is a powerful jQuery plugin that allows you to create interactive and responsive tables in your web applications. With the Yajra DataTables package for Laravel, integrating this feature becomes seamless. In this tutorial, we will implement a DataTable for managing tags in a Laravel 11 application.

Installation

First, we need to install the Yajra DataTables package via Composer. Run the following command in your terminal:

composer require yajra/laravel-datatables-oracle:"^11.0"
Enter fullscreen mode Exit fullscreen mode

Configuration

Next, you'll want to add the service provider to your application. Open config/app.php and add the following line to the providers array:

'providers' => [
    // ...
    Yajra\DataTables\DataTablesServiceProvider::class,
],
Enter fullscreen mode Exit fullscreen mode

Afterward, publish the configuration and assets using the following Artisan command:

php artisan vendor:publish --tag=datatables
Enter fullscreen mode Exit fullscreen mode

Creating the DataTable Class

Now, let’s create a DataTable class for managing tags. Execute the following command to create a new DataTable class:

php artisan make:datatable TagsDataTable
Enter fullscreen mode Exit fullscreen mode

Next, open the newly created TagsDataTable.php file located in the app/DataTables directory and populate it with the following code:

<?php

namespace App\DataTables;

use App\Models\Tag;
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 TagsDataTable extends DataTable
{
    public function dataTable(QueryBuilder $query): EloquentDataTable
    {
        return (new EloquentDataTable($query))
            ->addColumn('created_at', function ($tag) {
                return $tag->created_at->format('d-m-Y'); // Format date
            })
            ->addColumn('action', function ($tag) {
                return '
                    <div class="d-flex justify-content-center">
                        <a href="' . route('tags.edit', $tag->id) . '" class="text-success me-2">Edit</a>
                        <form action="' . route('tags.destroy', $tag->id) . '" method="POST" class="d-inline" onsubmit="return confirm(\'Are you sure you want to delete this tag?\');">
                            ' . csrf_field() . '
                            ' . method_field('DELETE') . '
                            <button type="submit" class="text-danger" style="border: none; background: none; cursor: pointer;">Delete</button>
                        </form>
                    </div>';
            })
            ->setRowId('id')
            ->rawColumns(['action']);
    }

    public function query(Tag $model): QueryBuilder
    {
        return Tag::query(); // Basic query for tags
    }

    public function html(): HtmlBuilder
    {
        return $this->builder()
                    ->setTableId('tags-table')
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->orderBy(1)
                    ->selectStyleSingle()
                    ->buttons([
                        Button::make('excel')->addClass('btn btn-primary'),
                        Button::make('csv')->addClass('btn btn-primary'),
                        Button::make('pdf')->addClass('btn btn-primary'),
                        Button::make('print')->addClass('btn btn-primary'),
                        Button::make('reset')->addClass('btn btn-secondary'),
                        Button::make('reload')->addClass('btn btn-secondary')
                    ]);
    }

    /**
     * Get the dataTable columns definition.
     */
    public function getColumns(): array
    {
        return [
            Column::computed('id')->title('ID')->addClass('text-center'),
            Column::computed('name')->title('Tag Name'),
            Column::computed('created_at')->title('Created At'),
            Column::computed('action')->title('Actions')->addClass('text-center'), // Center align actions
        ];
    }

    protected function filename(): string
    {
        return 'Tags_' . date('YmdHis');
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation of the DataTable Class

  • dataTable() Method: This method defines how the data is presented, including formatting for dates and adding action buttons for editing and deleting tags.
  • query() Method: This method retrieves all tags from the database.
  • html() Method: This method sets up the DataTable's configuration, including the table ID, columns, and buttons for export.
  • getColumns() Method: This method defines the columns that will appear in the DataTable.

Integrating DataTable into Your Controller

Next, you will integrate the TagsDataTable class into your controller. Open your TagController.php and modify the index method to utilize the DataTable:

use App\DataTables\TagsDataTable;

public function index(TagsDataTable $dataTable)
{
    return $dataTable->render('tags.index'); // Adjust view path as necessary
}
Enter fullscreen mode Exit fullscreen mode

Setting Up the Blade View

In your Blade view file (e.g., resources/views/tags/index.blade.php), add the following code to display the DataTable:

@extends('layouts.app')

@section('content')
<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
        <div class="p-4 sm:p-8 bg-white shadow sm:rounded-lg">
            <div class="">
                {{ $dataTable->table() }}
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
    {{ $dataTable->scripts() }}
@endsection
Enter fullscreen mode Exit fullscreen mode

Explanation of the Blade View

  • {{ $dataTable->table() }}: Generates the HTML for the DataTable.
  • {{ $dataTable->scripts() }}: Includes the necessary JavaScript for DataTables functionality.

Conclusion

In this guide, we implemented YajraBox DataTables in Laravel 11 to manage tags effectively. By following the steps outlined, you can create an interactive and responsive DataTable that enhances your web application's user experience.

With Yajra DataTables, you can easily manage data presentation, search, sort, and paginate your records with minimal effort. Feel free to modify the example to suit your specific application needs.

If you have any questions or need further assistance, please leave a comment below! Happy coding!

Top comments (0)