11

Laravel 8 - Custom server side search with datatable example

 1 year ago
source link: https://www.laravelcode.com/post/laravel-8-custom-server-side-search-with-datatable-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Laravel 8 - Custom server side search with datatable example

  41316 views

  1 year ago

Laravel

In this article, i will share with you how to make custom server-side search functionality in datatable with laravel 8 application. as you know datatable already provides the searching functionality. so, why we need it? yes, i agree with you but there you can search on only visible values searching. like in your debatable you show only "name" and "email" then you only able to search on those two fields values.

But if you want to search any values from your database's table then you need to use this functionality in your laravel 8 application. here i will share with you a very basic example for how to add custom server-side search functionality with your datatable listing in laravel 8 application.

Step - 1 : Route

In the first step, we need to write the following route in the route's file.

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

// Resource Route for users.
Route::resource('users', UserController::class);
// Route for get users for yajra post request.
Route::get('get-users', [UserController::class, 'getUsers'])->name('get-users');

Step - 2 : UserController

now, in this step, we write the following code in "getUsers()" function.

public function getUsers(Request $request, User $ser)
{
    $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 : Change in Blade File

into the last step we need to change in our blade file. write the following or implement there the following code.

@extends('articles.layout')

@section('style')
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
@endsection

@section('content')
<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>
@endsection

@section('script')
<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>
@endsection

i hope you like this small article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK