Laravel 10 Datatable Date Range Filter using AJAX

In this article, I will demonstrate how to implement a date range filter for DataTables in Laravel 10 using AJAX.

DataTables is a powerful jQuery plugin that allows you to enhance the functionality and interactivity of HTML tables. By adding a date range filter to your DataTables, you can enable users to filter data based on a specific date range, providing a more dynamic and targeted user experience.

With the combination of Laravel's robust backend framework and AJAX (Asynchronous JavaScript and XML) technology, we can create a seamless and responsive date range filter for our DataTables.

Throughout this tutorial, I will guide you through the step-by-step process of setting up the necessary components, configuring the AJAX requests, and implementing the date range filter logic.

So, let's dive in and learn how to create a Date Range Filter for DataTables using AJAX in Laravel 10.

Step 1: Set Up Laravel Project

Create a new Laravel project or use an existing one by running the following command in your terminal.

composer create-project laravel/laravel laravel-10-filter-example

 

Step 2: Install Yajra Datatable

Open your terminal and navigate to your Laravel project directory. Then, run the following command to install the required dependencies.

composer require yajra/laravel-datatables-oracle

 

Step 3: Add Dummy Users

Then, run the following command to start Tinker.

php artisan tinker

In the Tinker console, you can use the following code to create a dummy user.

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

 

 

Step 4: Implement Controller Logic

Create a new controller or use an existing one to handle the AJAX request and filter the data based on the selected date range. For example, let's assume you have a controller named UserController. Generate it using the following command.

php artisan make:controller UserController

app/Http/Controllers/UserController.php

<?php
     
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
use DataTables;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = User::select('*');
  
            if ($request->filled('from_date') && $request->filled('to_date')) {
                $data = $data->whereBetween('created_at', [$request->from_date, $request->to_date]);
            }
  
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->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');
    }
}

 

Step 5: Configure AJAX Route and Controller Method

In your routes/web.php file, define a route that will handle the AJAX request for filtering the data based on the date range. Open the file and add the following route definition.

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\UserController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('users', [UserController::class, 'index'])->name('users.index');

 

Step 6: Create Blade File

In this step, we will create a users.blade.php file.

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 10 Datatable Date Range Filter using AJAX - Techsolutionstuff</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.min.js"></script>
  
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
</head>
<body>
       
<div class="container">
    <h1>Laravel 10 Datatable Date Range Filter using AJAX - Techsolutionstuff</h1>
  
    <div style="margin: 20px 0px;">
        <strong>Date Filter:</strong>
        <input type="text" name="daterange" value="" />
        <button class="btn btn-success filter">Filter</button>
    </div>
  
    <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>
       
</body>
       
<script type="text/javascript">
  $(function () {
  
    $('input[name="daterange"]').daterangepicker({
        startDate: moment().subtract(1, 'M'),
        endDate: moment()
    });
        
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "{{ route('users.index') }}",
            data:function (d) {
                d.from_date = $('input[name="daterange"]').data('daterangepicker').startDate.format('YYYY-MM-DD');
                d.to_date = $('input[name="daterange"]').data('daterangepicker').endDate.format('YYYY-MM-DD');
            }
        },
        columns: [
            {data: 'id', name: 'id'},
            {data: 'name', name: 'name'},
            {data: 'email', name: 'email'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
  
    $(".filter").click(function(){
        table.draw();
    });
        
  });
</script>
</html>

 

 

Step 7: Run the Application

Now, run the laravel 10 application using the following command.

php artisan serve

 

Step 8: Conclusion

In this article, we explored the process of implementing a Date Range Filter for DataTables using AJAX in Laravel 10. By following the step-by-step guide, you have learned how to set up the necessary components, configure routes, implement controller logic, and create a Blade file to display the filtered data.

 


You might also like: 

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS