Laravel 10 Add Custom Search Filter To YajraBox Datatable

Reading Time: 7 minutes
498 Views

Searching and filtering data efficiently is a key necessity for many web applications, and Laravel, a sophisticated PHP framework, provides extensive capabilities for doing so.

YajraBox Datatables is a well-known tool for developing dynamic and feature-rich data tables. In this tutorial, you will learn how to apply a custom filter search to YajraBox Datatables in Laravel 10, allowing you to provide advanced filtering features to your users.

By the end of this tutorial, you’ll have the skills and knowledge to improve your Laravel 10 apps by adding custom filter search capabilities to YajraBox Datatables, allowing your users to filter data in a powerful and user-friendly manner.

Read More: How To Integrate Google Translator with Laravel 10 Tutorial

Let’s get started.

What is YajraBox Datatable?

The “Yajra DataTables” package is a popular Laravel package for constructing dynamic and interactive data tables. Yajra DataTables is a jQuery DataTables plugin extension that simplifies the creation and management of DataTables in Laravel applications.

It helps you to show data from your database tables in a paginated, searchable, and sortable style while requiring little scripting.

The Yajra DataTables package in Laravel has the following essential features and benefits:

  • Server-Side Processing
  • Customizable Columns
  • Search and Filtering
  • Sorting
  • Pagination
  • Ajax Integration
  • Responsive Design
  • Integration with Laravel Blade Templates

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

How To Generate Fake Data in Laravel?

Assuming you have users table created in your application database. And also your application contains User.php model file inside /app/Http/Models folder.

Here, you will generate fake data for users table.

Open Tinker Shell,

php artisan tinker

Generate 200 fake rows for users table,

>>> User::factory()->count(200)->create()

Users table view with data,

How To Install YajraBox Datatable in Laravel?

To install yajrabox, run this command:

composer require yajra/laravel-datatables-oracle

Read More: Laravel 10 Generate Custom Validation Error Messages

While installation of this package,

Setup Data Controller

Open project terminal and run this command,

php artisan make:controller UserController

It will create UserController.php file inside /app/Http/Controllers folder.

Open file and write this code into it,

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Str;

class UserController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {

            $data = User::latest()->get();

            return Datatables::of($data)
                ->addIndexColumn()
                ->filter(function ($instance) use ($request) {
                    if (!empty($request->get('email'))) {
                        $instance->collection = $instance->collection->filter(function ($row) use ($request) {
                            return Str::contains($row['email'], $request->get('email')) ? true : false;
                        });
                    }

                    if (!empty($request->get('search'))) {
                        $instance->collection = $instance->collection->filter(function ($row) use ($request) {
                            if (Str::contains(Str::lower($row['email']), Str::lower($request->get('search')))) {
                                return true;
                            } else if (Str::contains(Str::lower($row['name']), Str::lower($request->get('search')))) {
                                return true;
                            }

                            return false;
                        });
                    }
                })
                ->addColumn('action', function ($row) {

                    $btn = '<a href="javascript:void(0)" class="edit btn btn-primary btn-sm">View</a>';

                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        return view('users');
    }
}

Setup Data View Template

Create a fie users.blade.php inside /resources/views folder.

Open file and write this code into it,

<!DOCTYPE html>
<html>

<head>
    <title>Laravel 10 Add Custom Search Filter To YajraBox Datatable</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js"></script>
    <style type="text/css">
    body {
        background-color: #b4d7bd;
    }
    </style>
</head>

<body>
    <div class="container py-5">
        <div class="card">
            <div class="card-header text-center">
                <h3 style="font-size: 19px;padding: 10px;">Laravel 10 Add Custom Search Filter To YajraBox Datatable</h3>
            </div>
            <div class="card-body">
                <input type="text" name="email" class="form-control searchEmail" placeholder="Search for Email Only...">
                <br>

                <table class="table table-bordered data-table">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th width="100px">Action</th>
                        </tr>
                    </thead>

                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>

<script type="text/javascript">
$(function() {

    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "{{ route('users.index') }}",
            data: function(d) {
                d.email = $('.searchEmail').val(),
                    d.search = $('input[type="search"]').val()
            }
        },
        columns: [{
                data: 'DT_RowIndex',
                name: 'DT_RowIndex'
            },
            {
                data: 'name',
                name: 'name'
            },
            {
                data: 'email',
                name: 'email'
            },
            {
                data: 'action',
                name: 'action',
                orderable: false,
                searchable: false
            },
        ]
    });

    $(".searchEmail").keyup(function() {
        table.draw();
    });

});
</script>

</html>

Add Route

Open web.php file from /routes folder. Add this route into it,

//...
use App\Http\Controllers\UserController;

//...
Route::get('users', [UserController::class, 'index'])->name("users.index");
//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/users

Read More: How To Get env Variable inside Laravel Blade Templates

List View,

List View with search filter keyword,

That’s it.

We hope this article helped you to learn about Laravel 10 Add Custom Search Filter To YajraBox Datatable Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.