How To Set Date Range Filter In Datatables In Laravel

  Dec 2023
  ITSolutionsGuides
  Category: Laravel
How To Set Date Range Filter In Datatables In Laravel

Welcome To ITSolutionsGuides,

Lets learn How To Set Date Range Filter In Datatables In Laravel using it solutions guides. When we have a bulk amount of data we need to see or filter the data datewise so we need to add date filter in our laravel application. In this example we will use Yajra Datatables for displaying the data since by default in provides good pagination and filtering options. For creating the date filter we use the input date field to get the date to be filtered and then send the data through the ajax request and the display the filtered data from the database in the datatable. This example can be used in all Laravel 8, Laravel 9 ,Laravel 10 versions as well. So lets see How To Set Date Range Filter In Datatables In Laravel using it solutions guides.
Learn to implement a date range filter in DataTables within a Laravel environment. Enhance your web application by efficiently managing and displaying data with this insightful it solutions guides tutorial

Let's Create Controller

Lets install the Yajra Datatable in our laravel application, for detailed explanation follow this link,
Install Yajra Datatable In Laravel
after installing the datatable we are going to display the data in the datatable , so lets create some dummy records using the Factory tinker in laravel, for detailed explanation follow this link,
Generate Dummy Records using Factory Tinker
after generating the dummy records lets create the controller using the following artisan command,
php artisan make:controller UserController for detailed explanation about creating the controller, follow this link,
Create Controller Using Artisan Command

In the controller we will write all the functions inside the if($request->ajax()) since the function is called from ajax request and to execute only when the ajax request in made. Then we need to check wheather we get the date and then we will filter the data from the database. After fetching the data we need to return the data in the Datatable where we can add or customize the columns.


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');
    }
}

Let's Create Routes

lets create the required routes,

routes/web.php

<?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');

Let's Create Blade

Lets design the view page, While creating the view page we also need to add the Datatable Script and styling links, Also we need to add the input date field to select the date to filter the date, After selecting the date and click filter button the filter function will be executed to draw() the table data.

resources/views/users.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How To Set Date Range Filter In Datatables In Laravel</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>How To Set Date Range Filter In Datatables In Laravel</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>

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides