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
How to Install Node JS and NPM on Ubuntu 22.04
How to Install Node JS and NPM...

Hey fellow Ubuntu enthusiasts! 🐧✨ If you're looking to step into the awesome world of Node.js and npm for your web d...

Read More

Jan-12-2024

Carbon Add Minutes To Date In Laravel 9
Carbon Add Minutes To Date In...

In this article, we'll explore how to add minutes to a date in Laravel 8, Laravel 9 and Laravel 10 using Carbon...

Read More

Nov-23-2022

How To Image Optimization In Laravel 9 Using Spatie
How To Image Optimization In L...

In this article, we will see how to image optimization in laravel 9 using spatie. Here, we will learn about image o...

Read More

Feb-10-2023

Laravel 8 REST API With Passport Authentication
Laravel 8 REST API With Passpo...

Hello Guys,  Today I will give you example of laravel 8 REST API with passport authentication. Also perform...

Read More

May-31-2021