Custom filter/Search with Laravel Datatables Example

By Hardik Savani | May 16, 2019 | | 7358 Viewer | Category : PHP Laravel


Here, i want to show you how to add custom search with yajra datatables laravel. if you need to add custom filter like for datepicker, dropdown or specific fields of database then you can do it using laravel datatable.

Laravel yajra datatables provide default global search, in that search it will search entire row of table. But if you need to add for only one specific column like for created date search with datepicker or status with dropdown then you must have to implement custom filtering in your datatable.

Bellow i write step by step for how to add custom search filter with laravel 5.8 datatables. just follow few steps and you will get simple example:

Step 1: Install Laravel 5.8

In this step, if you haven't laravel 5.8 application setup then we have to get fresh laravel 5.8 application. So run bellow command and get clean fresh laravel 5.8 application.

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

Step 2 : Install Yajra Datatable Package

We need to install yajra datatable composer package for datatable, so you can install using following command:

composer require yajra/laravel-datatables-oracle

After that you need to set providers and alias.

config/app.php

.....

'providers' => [

....

Yajra\DataTables\DataTablesServiceProvider::class,

]

'aliases' => [

....

'DataTables' => Yajra\DataTables\Facades\DataTables::class,

]

.....

Step 3: Create Dummy Records

In this step, we will create some dummy users using tinker factory. so let's create dummy records using bellow command:

php artisan tinker

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

Step 4: Create Route

In this is step we need to create route for datatables layout file and another one for getting data. so open your routes/web.php file and add following route.

routes/web.php

Route::get('users', ['uses'=>'UserController@index', 'as'=>'users.index']);

Step 5: Create Controller

In this point, now we should create new controller as UserController. this controller will manage layout and getting data request and return response, so put bellow content in controller file:

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use App\User;

use Illuminate\Http\Request;

use DataTables;

use Illuminate\Support\Str;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

if ($request->ajax()) {

$data = User::latest()->get();

return Datatables::of($data)

->addIndexColumn()

->filter(function ($instance) use ($request) {

if (!empty($request->get('email'))) {

$instance->collection = $instance->collection->filter(function ($row) use ($request) {

return Str::contains($row['email'], $request->get('email')) ? true : false;

});

}

if (!empty($request->get('search'))) {

$instance->collection = $instance->collection->filter(function ($row) use ($request) {

if (Str::contains(Str::lower($row['email']), Str::lower($request->get('search')))){

return true;

}else if (Str::contains(Str::lower($row['name']), Str::lower($request->get('search')))) {

return true;

}

return false;

});

}

})

->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 6: Create View

In Last step, let's create users.blade.php(resources/views/users.blade.php) for layout and we will write design code here and put following code:

resources/views/users.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Custom filter/Search with Laravel Datatables Example</title>

<meta name="csrf-token" content="{{ csrf_token() }}">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">

<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.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.10.16/js/jquery.dataTables.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>

</head>

<body>

<div class="container">

<h1>Custom filter/Search with Laravel Datatables Example</h1>

<input type="text" name="email" class="form-control searchEmail" placeholder="Search for Email Only...">

<br>

<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 () {

var table = $('.data-table').DataTable({

processing: true,

serverSide: true,

ajax: {

url: "{{ route('users.index') }}",

data: function (d) {

d.email = $('.searchEmail').val(),

d.search = $('input[type="search"]').val()

}

},

columns: [

{data: 'DT_RowIndex', name: 'DT_RowIndex'},

{data: 'name', name: 'name'},

{data: 'email', name: 'email'},

{data: 'action', name: 'action', orderable: false, searchable: false},

]

});

$(".searchEmail").keyup(function(){

table.draw();

});

});

</script>

</html>


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

php artisan serve

Now you can open bellow url on your browser:

http://localhost:8000/users

You can get more information about package from here : Click Here.

I hope it can help you...



Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
***Do you want me hire for your Project Work? Then Contact US.


We are Recommending you: