Server Side Custom Search in Datatables

Websolutionstuff | Apr-05-2021 | Categories : Laravel PHP

In this example we will discuss about server side custom search in datatable. Datatable provides default searching functionality but there you can search on only visible values searching. like in your debatable you show only "user_name" and "email" then you only able to search on those two fields values.

So, Here we will see how to custom search in datatable in laravel, if you want to filter hidden data from database then you need to add datatable custom search or laravel datatable custom filter.

 

Step 1 : Create Route for Server Side Custom Search in Datatable

 

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::resource('users', UserController::class);
Route::get('getusers', [UserController::class, 'getUsers'])->name('getusers');

 

 

Step 2 : Add Code in Controller

 

Now, we need to add below code in UserController.

public function getUsers(Request $request, User $user)
{
    $input = \Arr::except($request->all(),array('_token', '_method'));

    $data = User::where('is_active', '1');
    if(isset($input['username'])) {
        $data = $data->where('username', 'like', '%'.$input['username'].'%');
    }
    if(isset($input['country'])) {
        $data = $data->where('country', $input['country']);
    }
    $data = $data->get();
    return \DataTables::of($data)
        ->addColumn('Actions', function($data) {
            return '<button type="button" data-id="'.$data->id.'" data-toggle="modal" data- 
            target="#DeleteUserModal" class="btn btn-danger btn-sm" 
            id="getDeleteId">Delete</button>';
        })
        ->rawColumns(['Actions'])
        ->make(true);
} 

 

Step 3 : Make Changes in Blade File

 

<!DOCTYPE html>
<html>
<head>
    <title>Server Side Custom Search in Datatables - websolutionstuff.com</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.20/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.20/js/dataTables.bootstrap4.min.js"></script>
</head>
<body>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="card-title">
                        Advance Searching
                    </div>
                    <form method="GET" id="search-form">
                        <div class="row">
                            <div class="col-lg-3">
                                <input type="text" class="form-control adv-search-input" placeholder="User Name" name="username" value="{{ (isset($_GET['username']) && $_GET['username'] != '')?$_GET['username']:'' }}">
                            </div>
                            <div class="col-lg-3">
                                <input type="text" class="form-control adv-search-input" placeholder="Country" name="country" value="{{ (isset($_GET['country']) && $_GET['country'] != '')?$_GET['country']:'' }}">
                            </div>
                            <div class="col-lg-12">
                                <hr>
                                <button class="btn btn-success" type="submit" id="extraSearch">Search</button>
                                <a class="btn btn-danger" href="#">Reset</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-body">
                    <div class="card-title">
                        {{ __('Article Listing') }}
                        <button style="float: right; font-weight: 900;" class="btn btn-info btn-sm" type="button"  data-toggle="modal" data-target="#CreateArticleModal">
                            Create Article
                        </button>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered datatable">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Name</th>
                                    <th>Description</th>
                                    <th width="150" class="text-center">Action</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        // init datatable.
        var dataTable = $('.datatable').DataTable({
            processing: true,
            serverSide: true,
            autoWidth: false,
            pageLength: 5,
            // scrollX: true,
            "order": [[ 0, "desc" ]],
            ajax: {
                url: '{{ route('get-users') }}',
                    data: function (d) {
                    d.username = $('input[name=username]').val();
                    d.country = $('input[name=country]').val();
                }
            },
            columns: [
                {data: 'id', name: 'id'},
                {data: 'name', name: 'name'},
                {data: 'email', name: 'email'},
                {data: 'Actions', name: 'Actions',orderable:false,serachable:false,sClass:'text-center'},
            ]
        });
    });
</script>
</html>

 

Recommended Post
Featured Post
Laravel Authentication Using Breeze
Laravel Authentication Using B...

In this article, we will share you new information about laravel authentication using a breeze. Laravel Breeze...

Read More

Feb-05-2021

How To Create Dynamic Bar Chart In Laravel 9
How To Create Dynamic Bar Char...

In this article, we will see how to create a dynamic bar chart in laravel 9. Bar charts are used to represent...

Read More

Mar-21-2022

Laravel 9 Livewire Pagination Example
Laravel 9 Livewire Pagination...

In this article, we will see laravel 9 livewire pagination example. we will learn how to create a laravel live...

Read More

Sep-29-2022

How To Check Email Already Exist Or Not In Laravel
How To Check Email Already Exi...

In this article, we will show how to check whether the email already exists or not in laravel. Also, we will check...

Read More

Aug-07-2020