Custom Search in Yajra Datatables Laravel 7/6

Laravel 7/6 custom filter (search) in DataTable, you will learn how you can add a custom filter or search in yajra DataTables and & display data without reloading the whole page on dataTables. with example. We will also provide a demo of this example.

This example tutorial also work with laravel 7.x version.

Laravel Yajra data tables package provide has much functionality for searching, sorting, adding the column. In this laravel yajra data table, we will learn how to add a custom field and searching data without reloading the data table.

DataTables is a plug-in for the jQuery Javascript library. Laravel Yajra DataTables Package provides many functionalities like searching, sorting, pagination on the table.

Laravel Add Custom Filter In DataTables

Just follow few steps from scratch and successfully add custom date search filter on dataTables :

  • Install laravel Fresh Setup
  • Configuration .evn file
  • Run Migration
  • Install Yajra DataTables
  • Add Fake Data
  • Create Route, Controller & Blade View
  • Start Development Server
  • Conclusion

Install laravel Fresh Setup

First We need Download fresh Laravel setup. Use the below command to download the laravel 6 fresh setup on your system.

composer create-project --prefer-dist laravel/laravel LaravelYajra

Configuration .env file

In this step, we will set database credential in .env file

laravel datatables
configuration.evn

Run Migration

Next, go to your web application root directory and type the following command migration:

php artisan migrate

This command will create tables in our database.

If you found any database raleted error on your command so, go to app\Providers\AppServiceProvider.php and update the below given code into your appServiceProvider.php file:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Install Yajra Datatable Package in Laravel

Now We will Install Yajra Datatable Packages in your laravel web application. Use the below command and install yajra packages in your laravel application.

composer require yajra/laravel-datatables-oracle

After successfully Install Yajra Datatable Packages, open config/app.php file and add service provider and alias.

config/app.php

 'providers' => [

   Yajra\Datatables\DatatablesServiceProvider::class,

 'aliases' => [

  'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]

After set providers and aliases then publish vendor run by following command.

php artisan vendor:publish

Add Fake Records

We need to add some records in database. Use the below command for add fake records in your database.

php artisan tinker

After run the php artisan tinker. Use the below command. This command will add 150 fake records in your database

>>> factory(App\User::class, 150)->create();

Create Route, Controller & Blade View


Add Route

Now we will add routes in web.php file as like below.

Open routes/web.php file

Route::get('users', 'UsersController@index');
Route::get('users-list', 'UsersController@usersList');

Create Controller

We need to create new controller UsersController that will manage two method. lets use this below command and create Controller.

php artisan make:controller UsersController

Now open the controller let’s go to the => app/Http/Controllers/UsersController.php. Put the below Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Redirect,Response,DB,Config;
use Datatables;
use App\User;

class UsersController extends Controller
{
    public function index()
    {
        return view('users');
    }
    public function usersList()
    {
        $usersQuery = User::query();

        $start_date = (!empty($_GET["start_date"])) ? ($_GET["start_date"]) : ('');
        $end_date = (!empty($_GET["end_date"])) ? ($_GET["end_date"]) : ('');

        if($start_date && $end_date){

         $start_date = date('Y-m-d', strtotime($start_date));
         $end_date = date('Y-m-d', strtotime($end_date));

         $usersQuery->whereRaw("date(users.created_at) >= '" . $start_date . "' AND date(users.created_at) <= '" . $end_date . "'");
        }
        $users = $usersQuery->select('*');
        return datatables()->of($users)
            ->make(true);
    }
}

Create Blade View

Next, create users.blade.php file in resources/views/ folder and copy past following code.

In this blade view file we will add custom date filter on datatables.

<!DOCTYPE html>

<html lang="en">
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel DataTable With Custom Filter - Tuts Make</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link  href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
</head>
<body>
 <div class="container">
   <h2>Laravel DataTable With Custom Filter - Tuts Make</h2>
   <br>
   <div class="row">
    <div class="form-group col-md-6">
    <h5>Start Date <span class="text-danger"></span></h5>
    <div class="controls">
        <input type="date" name="start_date" id="start_date" class="form-control datepicker-autoclose" placeholder="Please select start date"> <div class="help-block"></div></div>
    </div>
    <div class="form-group col-md-6">
    <h5>End Date <span class="text-danger"></span></h5>
    <div class="controls">
        <input type="date" name="end_date" id="end_date" class="form-control datepicker-autoclose" placeholder="Please select end date"> <div class="help-block"></div></div>
    </div>
    <div class="text-left" style="
    margin-left: 15px;
    ">
    <button type="text" id="btnFiterSubmitSearch" class="btn btn-info">Submit</button>
    </div>
    </div>
    <br>
    <table class="table table-bordered" id="laravel_datatable">
       <thead>
          <tr>
             <th>Id</th>
             <th>Name</th>
             <th>Email</th>
             <th>Created at</th>
          </tr>
       </thead>
    </table>
 </div>
 <script>
 $(document).ready( function () {
     $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
  $('#laravel_datatable').DataTable({
         processing: true,
         serverSide: true,
         ajax: {
          url: "{{ url('users-list') }}",
          type: 'GET',
          data: function (d) {
          d.start_date = $('#start_date').val();
          d.end_date = $('#end_date').val();
          }
         },
         columns: [
                  { data: 'id', name: 'id' },
                  { data: 'name', name: 'name' },
                  { data: 'email', name: 'email' },
                  { data: 'created_at', name: 'created_at' }
               ]
      });
   });

  $('#btnFiterSubmitSearch').click(function(){
     $('#laravel_datatable').DataTable().draw(true);
  });
</script>
</body>
</html>

Start Development Server

In this step, we will use the php artisan serve command . It will start your server locally

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://127.0.0.1:8000/users  

8. Conclusion

In this article, we have successfully added a custom search box filter on dataTables. our examples run quickly.

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Custom Search in Yajra Datatables Laravel 7/6

  1. Hi Devendra,

    Great example!

    All the code samples I a finding online for adding Search and Date Filter do not also include Edit/Delete options in the table columns for each row. Do you have any suggestions or any idea how to modify for that?

Leave a Reply

Your email address will not be published. Required fields are marked *