Laravel Yajra Datatable with custom Search Filter
We will learn how to use yajra data table using custom and search filters together. Also, you can use it as per your requirement of code.
routes/web.php
Route::get('get-datatable-response','HomeController@getdataTableResponse');
app\Http\Controller\HomeController.php
public function getdataTableResponse(Request $request) {
if($request->ajax()) {
$orderby = $request->input('order.0.column');
$sort['col'] = $request->input('columns.' . $orderby . '.data');
$sort['dir'] = $request->input('order.0.dir');
if ($request->has('search') && ! is_null($request->get('search')['value']) ) {
$regex = $request->get('search')['value'];
$data = DB::table('users')
->orWhere('firstname','LIKE','%'. $regex .'%')
->orWhere('email','LIKE','%'. $regex .'%')
->orderBy($sort['col'], $sort['dir'])
->get();
} else {
$data = \DB::table('users')
->orderBy($sort['col'], $sort['dir'])
->latest();
}
return DataTables::of($data)
->addIndexColumn()
->addColumn('actions', function($row) {
$btn = '<button type="button" data-id="'.$row->id.'" data-toggle="modal" data-target="#AddEditModal" class="btn-edit btn btn-success btn-sm">Edit</button>
<button type="button" data-id="'.$row->id.'" class="btn-delete btn btn-danger btn-sm">Delete</button>';
return $btn;
})
->editColumn('updated_at',function($object) {
$final_date = new \Carbon\Carbon($object->updated_at);
return $final_date->shortRelativeDiffForHumans();
})
->editColumn('created_at',function($object) {
$final_date = new \Carbon\Carbon($object->created_at);
return $final_date->shortRelativeDiffForHumans();
})
->rawColumns('actions')
->make(true);
}
}