Filter Data Between Two Dates in Yajra Datatables in Laravel

Hello Artisan,

In this example tutorial, I will show you how to filter data between two dates in yajra datatables in Laravel 9. You know that sometimes we need to filter data in our data table. But there is no option to do it from datatable package from yajra datatable.

So I am here to show you an example of datatables date range filter example in Laravel 9 application with yajra datatable. So, Here I will discuss how to make the Datarange filter in Laravel 9 Datatable with Server-side processing by using yajra Datatables package by using Ajax request. 

We will take requests, one if from_date and the other is to_date, and using those dates, I will filter data. See the below image that what we are going to create:

laravel-yajra-datatable-filter-example

Step 1 : Install Laravel

I am going to start from scratch. So download a fresh Laravel project using the below command:

composer create-project laravel/laravel example-app

 

Step 2: Install yajra Datatable

In this step, we have to install yajra datatable package. So run the below command:

composer require yajra/laravel-datatables-oracle

 

Update config/app.php with the following code:

config/app.php

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

 

Step 3: Create Controller

Now in this step, we need a controller to filter our data. Create a controller and update it like below:

app\Http\Controllers\DateRangeController 

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class DateRangeController extends Controller
{
    function index(Request $request)
    {
     if(request()->ajax())
     {
      if(!empty($request->from_date))
      {
       $data = DB::table('tbl_order')
         ->whereBetween('order_date', array($request->from_date, $request->to_date))
         ->get();
      }
      else
      {
       $data = DB::table('tbl_order')
         ->get();
      }
      return datatables()->of($data)->make(true);
     }
     return view('daterange');
    }
}

 

Step 4: Create Route

In this step, we will create the route. Update the below file like that:

routes/web.php

Route::resource('daterange', 'DateRangeController');

 

Step 5: Create View Blade File

Here for the date range filter, we have used the Date picker library for selecting dates. Below you can find the source of the below file.

resources/views/daterange.blade.php

 

Read also: Upload Large CSV File using Queue Job Batching in Laravel

 

We are all set to go. Now you can test by visiting the following url:

 

URL
http://127.0.0.1:8000/daterange

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js