Laravel 6 Datatables Custom Filter Example Tutorial

In this laravel datatables tutorial, We would love to share with you how to add custom date filter and custom search box field & display data without page refresh on datatables. Laravel Yajra datatables package provide has many functionality for searching, sorting, adding column. In this laravel yajra datatable we will learn how to add custom field and searching data without reload the datatable.

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

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

DataTables Custom Filter

Contents

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

Install Laravel

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

We need to do  migration of tables using below command:

php artisan migrate

This command will create tables in our database.

Install Yajra Datatable Package in Laravel

Now We will Install Yajra Datatable Packages in your laravel 5.7 setup. 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', '[email protected]');
Route::get('users-list', '[email protected]');

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;
class UsersController extends Controller
{
    public function index()
    {
        return view('users');
    }
    public function usersList()
    {   
        $usersQuery = Users::query();

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

        if($start_date &amp;&amp; $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 - W3path</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="http://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 - W3path</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 add 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.

28 Comments

  1. sirglio frei said:

    I want to show thanks to you for rescuing me from this type of trouble. Right after checking throughout the the net and obtaining advice which were not powerful, I believed my life was over. Living without the approaches to the difficulties you’ve resolved through your short post is a serious case, and ones which may have badly damaged my entire career if I had not noticed your web site. Your primary skills and kindness in playing with almost everything was crucial. I don’t know what I would’ve done if I had not come across such a stuff like this. I can also at this point look ahead to my future. Thank you so much for the reliable and effective guide. I won’t think twice to suggest your web sites to any individual who would need care on this topic.

    October 11, 2019
    Reply
  2. ERIC KWAKYE said:

    Hi Senior..
    Your aryicle is one of the best.
    If you can do one with datatables with export features and crud all in one.
    it will be appreciated. i tried the one datatables as a service with crud but whole lot of issues.

    November 12, 2019
    Reply
  3. Mitchel said:

    I am curious to find out what blog system you are working with?
    I’m having some minor security problems with my latest blog and I would
    like to find something more safeguarded. Do you have any suggestions?

    Here is my blog cheap flights

    January 31, 2021
    Reply
  4. Gabriel said:

    Hi, Neat post. There is an issue together with your site in internet explorer,
    could check this? IE still is the marketplace chief and a huge section of people will miss your fantastic writing due to this problem.

    my web site cheap flights

    February 1, 2021
    Reply
  5. Veola said:

    Woah! I’m really enjoying the template/theme of this blog.

    It’s simple, yet effective. A lot of times it’s hard to get that “perfect balance” between superb
    usability and visual appearance. I must say you have done a great job with this.
    In addition, the blog loads very quick for me on Chrome. Excellent Blog!

    Here is my page cheap flights

    February 1, 2021
    Reply
  6. Darrell said:

    Howdy would you mind letting me know which webhost you’re utilizing?
    I’ve loaded your blog in 3 completely different web browsers and
    I must say this blog loads a lot quicker then most. Can you suggest a good web hosting
    provider at a reasonable price? Thanks, I appreciate it!

    Here is my page cheap flights (tinyurl.com)

    February 2, 2021
    Reply
  7. Milagro said:

    My brother suggested I would possibly like this website.
    He was once entirely right. This post actually made my
    day. You can not believe just how much time I had spent for this information! Thanks!

    My web page – cheap flights

    February 2, 2021
    Reply
  8. Madison said:

    I like the valuable information you provide in your articles.
    I’ll bookmark your blog and check again here regularly.

    I’m quite certain I will learn plenty of new stuff right
    here! Best of luck for the next!

    Also visit my homepage … cheap flights; http://tinyurl.com/yxs8qoyd,

    February 3, 2021
    Reply
  9. KuikCuddy said:

    tricare viagra viagra price viagra via paypal

    February 5, 2021
    Reply
  10. Kbcxbype said:

    canadian pharmacy drugs online motion sickness pharmacy online no prescription

    February 6, 2021
    Reply
  11. Phillis said:

    I think that everything published was very reasonable.
    But, consider this, suppose you added a little information? I am not suggesting your content is
    not good, however what if you added a headline that grabbed folk’s attention? I mean Laravel 6 Datatables Custom Filter Example Tutorial – W3path
    is a little vanilla. You should look at Yahoo’s front
    page and note how they create post titles to grab viewers interested.
    You might add a related video or a related picture or two to get readers excited about what you’ve got to
    say. In my opinion, it could make your posts a little bit more interesting.

    Here is my page … cheap flights (tinyurl.com)

    February 12, 2021
    Reply
  12. Kvaxbype said:

    cash advance interest nab express payday advance what to do when you can’t pay a payday loan

    February 13, 2021
    Reply

Leave a Reply

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