Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How can I add custom filters to Yajra Datatables in Laravel 11


How can I add custom filters to Yajra Datatables in Laravel 11


To add custom filters to Yajra Datatables in Laravel 11, you need to follow these steps:

1. Install Yajra Datatables Package: Ensure you have Yajra Datatables installed in your Laravel application. If not, you can install it via Composer.

sh
    composer require yajra/laravel-datatables
    

2. Publish Configuration: Publish the configuration file if you haven't already.

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

3. Create a Datatable Class: Create a Datatable class using Artisan command.

sh
    php artisan datatables:make UsersDataTable
    

4. Add Custom Filters in the Datatable Class: In your `UsersDataTable` class, you can add custom filters in the `html` method and apply them in the `query` method.

php
    use Yajra\DataTables\Html\Column;

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->addAction(['width' => '80px'])
            ->parameters([
                'dom'     => 'Bfrtip',
                'order'   => [[1, 'asc']],
                'buttons' => ['csv', 'excel', 'pdf', 'print', 'reset', 'reload'],
                'initComplete' => 'function() {
                    this.api().columns().every(function () {
                        var column = this;
                        var input = document.createElement("input");
                        $(input).appendTo($(column.footer()).empty())
                        .on(\'change\', function () {
                            column.search($(this).val(), false, false, true).draw();
                        });
                    });
                }',
            ]);
    }

    protected function getColumns()
    {
        return [
            'id',
            'name',
            'email',
            Column::computed('created_at')
                  ->title('Created At'),
            Column::computed('updated_at')
                  ->title('Updated At'),
        ];
    }
    

5. Apply Filters in the Query: In the `query` method of your `UsersDataTable` class, apply the custom filters.

php
    public function query(User $model)
    {
        $query = $model->newQuery();

        if ($name = $this->request()->get('name')) {
            $query->where('name', 'like', "%{$name}%");
        }

        if ($email = $this->request()->get('email')) {
            $query->where('email', 'like', "%{$email}%");
        }

        return $this->applyScopes($query);
    }
    

6. Add HTML for Filters in the View: Add the necessary HTML for the filters in your Blade view. For instance:

html
    <table class="table table-bordered" id="users-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Created At</th>
                <th>Updated At</th>
            </tr>
        </thead>
        <thead>
            <tr>
                <th><input type="text" placeholder="Search ID"></th>
                <th><input type="text" placeholder="Search Name"></th>
                <th><input type="text" placeholder="Search Email"></th>
                <th><input type="text" placeholder="Search Created At"></th>
                <th><input type="text" placeholder="Search Updated At"></th>
            </tr>
        </thead>
    </table>
    

7. Initialize Datatables in the View: Finally, initialize Datatables in your Blade view.

javascript
    $(function() {
        $('#users-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: '{!! route('users.data') !!}',
                data: function (d) {
                    d.name = $('input[name=name]').val();
                    d.email = $('input[name=email]').val();
                }
            },
            columns: [
                { data: 'id', name: 'id' },
                { data: 'name', name: 'name' },
                { data: 'email', name: 'email' },
                { data: 'created_at', name: 'created_at' },
                { data: 'updated_at', name: 'updated_at' }
            ]
        });

        $('#users-table').on('keyup', 'input', function() {
            $('#users-table').DataTable().draw(true);
        });
    });
    

This setup will allow you to have custom filters for your Yajra Datatables in Laravel 11. Adjust the filter fields and query logic as needed for your specific use case.