Laravel Yajra Datatables searchable not working on desire column - laravel

I have datatables column as such:
var showMasterUserTable = function () {
masterIcon = $('#master_user_table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: {
url: ROOT + 'master-voucher-bit-x/data',
},
columns: [
{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
searchable: false,
orderable: false
},
{
data: 'voucher_code',
name: 'voucher_code',
},
{
data: 'status',
name: 'status',
},
{
data: 'track',
name: 'track',
},
{
data: 'user_use',
name: 'user_use',
orderable: true
},
{
data: 'progress',
name: 'progress',
},
{
data: 'quiz_score',
name: 'quiz_score',
},
{
data: 'urlQr',
name: 'urlQr',
}
]
});
};
As long as i know from the yajra and datatables docs that searchable and orderable is default to be true when it remains unwritten, i have encounter the issue where searchable only search for voucher_code column no matter if i set all the searchable to true. I want to search for user_use column instead. If i set all the searchable to false, the table data cannot be loaded. How should i overcome it? Here's my controller code:
{
$model = VoucherBitX::select('voucher_bit_x.*', 'users.email')
->join('users', 'voucher_bit_x.user_id', '=', 'users.id')
->orderBy("voucher_bit_x.redeem_at","DESC");
return DataTables::of($model)
->addColumn('status', function ($data) {
if($data->status > 0)
$status = '<div><span class="badge badge-success"> Available </span></div>';
else
$status = '<div><span class="badge badge-danger"> Not Available </span></div>';
return $status;
})
->addColumn('urlQr', function ($data) {
$user = UserApp::find($data->user_id);
$a = "";
if(!empty($user) && isset($user->ref_id)){
$quiz = QuizScore::where("track_id",$data->track_id)->where("user_id",$data->user_id)->first();
if($quiz && $quiz->status){
$track = Track::find($data->track_id);
$urlQr = 'https://xxx.id/api/certificate/'.base64_encode(json_encode(["user_id"=>$user->id,"slug"=>$track->slug,"track_id"=>$track->id]));
$a = 'Download Certificate';
}
}
return $a;
})
->addColumn('quiz_score', function ($data) {
$score = 0;
$quiz = QuizScore::where("track_id",$data->track_id)->where("user_id",$data->user_id)->first();
if($quiz){
$score = $quiz->score;
}
return $score;
})
->addColumn('progress', function ($data) {
$progress = 0;
$solve = Track::userProgress($data->user_id,$data->track_id);
if(!empty($solve)){
$progress = $solve;
}
return $progress."%";
})
->addColumn('user_use', function ($data) {
$user = UserApp::find($data->user_id);
if(!empty($user))
return $user->name." (".$user->email.")";
return '-';
})
->addColumn('track', function ($data) {
$track = Track::find($data->track_id);
return isset($track->title)?$track->title:"";
})->rawColumns(['quiz_score','status','user_use','track','urlQr'])
->addIndexColumn()->make(true);
}
*Edit:
I have realized that datatables returned a response that included used query like this:
New question: just where the hell that query json field configuration? On my eloquent query above there is no such thing as where and like query. Haven't found that things both in yajra and datatables documentation. What i want is to modify the where field to users.email instead voucher_bit_x.voucher_code

use columns.searchable
Using this parameter, you can define if DataTables should include this column in the filterable data in the table. You may want to use this option to disable search on generated columns such as 'Edit' and 'Delete' buttons for example.
$('#example').dataTable( {
"columnDefs":
[
{ "searchable": false, "targets": 0 }
]
});
This will disable the search of multiple columns as specified n the target. If you want multiple columns then try using
{ "searchable": false, "targets": [0,1,2] }
Where targets 0 1 and 2 are number of columns starting index from 0

Related

Displaying json data on datatables with laravel resources

I have some data i have stored in my table and i have cast to array and accessing it in my resource like this
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class JobRequests extends JsonResource
{
public $preserveKeys = true;
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
$data = DB::select('select order_data from orders where id=9');
return [
'email' => json_decode($data[0]->order_data)->personal_data->email,
'telephone_number' => json_decode($data[0]->order_data)->personal_data->telephone_number,
'car_registration' => json_decode($data[0]->order_data)->personal_data->car_registration,
'postal_code' => json_decode($data[0]->order_data)->personal_data->postal_address
/**
'commission' => function(){
$final_price = 700;
return (int)$final_price;
}
*/
];
}
}
My data looks like this
{
"personal_data": {
"email": "info#info.com",
"telephone_number": "0999",
"postal_address": "LON",
"car_registration": "GB BHG"
},
"inperson_diagnostic": {
"diagnostic_inspection": "67.30",
"car_wont_start_inspection": "67.30",
"plugin_diagnostic_inspection": "67.30"
},
"tyres": {
"front_wheels": 1,
"rear_wheels": 1,
"wheel_width": 45,
"wheel_profile": 1,
"wheel_rim": 1,
"speed_rating": "w",
"final_price": 90
},
"servicing_and_mot": {
"mot_with_collection_delivery": 75,
"major_service": 304.52,
"full_service": 203.45,
"interim_service": "149.70",
"vehicle_health_check": 50
},
"inspection_services": {
"premium_prepurchase_inspection": 146.38,
"standard_prepurchase_inspection": 104,
"basic_prepurchase_inspection": 86.44
},
"repairs": {
"ABS wheel speed sensor replacement": 964,
"ABS pump replacement": 712,
"Brake pedal switch replacement": 568,
"Air conditioning regas (R1234yf Gas ONLY)": 469
}
}
This is the function i am trying to fetch data with
//Fetch Job Requests
public function jrData(Request $request)
{
//$data = DB::select('select order_data from orders where id=9');
$jobRequest = new JobRequests($request);
$object_json = $jobRequest->toJson();
$object_array = (array)$object_json;
return Datatables::of($object_array)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'View';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
and this is my blade page
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! url('jrData') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'telephone_number', name: 'telephone_number' },
{ data: 'car_registration', name: 'car_registration' },
{ data: 'postal_code', name: 'postal_code' },
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
This is the data returned by my jrData
{"draw":0,"recordsTotal":1,"recordsFiltered":1,"data":[{"0":"{\"email\":\"info#info.com\",\"telephone_number\":\"0900\",\"car_registration\":\"KGB BHG\",\"postal_code\":\"00200\"}","action":"<a href=\"view_job_request\/\" class=\"edit btn btn-info btn-sm m-2\">View<\/a>","DT_RowIndex":1}],"input":[]}
I get this error on my blade file
DataTables warning: table id=users-table - Requested unknown parameter
'id' for row 0. For more information about this error, please see
http://datatables.net/tn/4
How can i display the data in the datatables?
Ok here is an example:
You have
$data = DB::select('select order_data from orders where id=9');
This really isn't going to give you the data you need.
Try doing this:
$data = YourModel::where('id',$id)->first();
$id is a dynamic id so you can run this to grab anything instead of being static. I'm guessing you are doing a post to get the data, so if you send that through it would be $request->id so you just set it to $id = $request->id; now you're fully dynamic in your eloquent.

Why is the link getting doubled sometimes when I use yajra-datatable for laravel?

Most of the time when I select a user in the users list, the link would go "localhost:8000/user/1" but sometimes is goes "localhost:8000/user/user/1". I can't remove the user in the link data = '<a href="user/' + data + '>' + data + '</a>'; because most of the time it shows the user page correctly.
This is the code under the UserController
public function getUsers(Request $request) {
if ( $request->ajax() ) {
...
return Datatables::of($data)
->addColumn('id', function($row) {
return $row['id'];
})
->addColumn('name', function($row) {
return $row['name'];
->rawColumns(['id', 'name'])
->make(true);
}
}
This is the script for users index.blade.php
<script type="text/javascript">
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url('users/list') }}",
columns: [
{
data: 'id',
name: 'id',
"render": function(data, type, row, meta) {
if(type === 'display'){
data = '<a href="user/' + data + '>' + data + '</a>';
}
return data;
}
},
{data: 'name', name: 'name'},
],
});
});
</script>
just add slash in the front of url
data = '<a href="/user/' + data + '>' + data + '</a>';
I think the thing causing the problem could be the href attribute because if you are on the "/user" page the href value "user/1" will add to that so it will give that result like "/user/user/1".
You should make an absolute value for that. Using this approach that could be accomplished. Try to make a complete URL to the user read page, like this:
$(function () {
var users_url = "{{config('app.url'}}/user/"; // <-- This should be the absolute URL to user page
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url('users/list') }}",
columns: [
{
data: 'id',
name: 'id',
"render": function(data, type, row, meta) {
if(type === 'display'){
data = '' + data + '';
}
return data;
}
},
{data: 'name', name: 'name'},
],
});
});

How to get the value from another table using id with Ajax and Laravel?

I was trying Yajra Datatable on Laravel and I found this on the tutorial where I get the values from a single table.
I have to compare the values of each column in the 1st table to the 2nd table like for example the 1st tables status is 1, it would check the status types table which status has the id of 1 and in this example 1 is pending so the datatable would be showing "Pending" instead of number 1
Below here is the code from the Controller:
public function index()
{
$documents = Documents::all();
$status = Status::all();
return view('document/index', compact('documents', 'status'));
}
public function getDocs(Request $request)
{
if ($request->ajax()) {
$docs = Documents::latest()->get();
return Datatables::of($docs)
->addIndexColumn()
->addColumn('action', function($row){
$actionBtn = 'Edit Delete';
return $actionBtn;
})
->rawColumns(['action'])
->make(true);
}
}
Here is from the document/index view:
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('documents.list') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'status', name: 'status'}
]
});
});
First Define relation between Status and Documents Model
Status Model:
public function docs(){
return $this->hasMany(Documents::class);
}
Documents Model:
public function state(){
return $this->belongsTo(Status::class, 'status');
# 'status' is the name of foreign key on documents table
}
Documents Controller:
public function getDocs(Request $request)
{
if ($request->ajax()) {
$docs = Documents::with('state')->select('documents.*')->latest();
# Here 'documents' is the name of table for Documents Model
# And 'state' is the name of relation on Document Model.
return Datatables::of($docs)
->addIndexColumn()
->addColumn('status_str', function($row){
# 'name' is the field in table of Status Model
return $row->state->name;
})
->addColumn('action', function($row){
$actionBtn = 'Edit Delete';
return $actionBtn;
})
->rawColumns(['action'])
->make(true);
}
}
Index View:
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('documents.list') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'status_str', name: 'state.name'}
]
});
});

datatable pagination in laravel

I am using laravel 5.0
I am also using datatable jquery plugin to display grid.
Controller mehtod
public function index() {
$jobs = \App\Job::orderBy('created_at', 'DESC')->limit(1000)->get();
return View::make('jobs.index', ['jobs' => $jobs]);
}
The issue:
Right now I hard-coded the ->limit(1000) to 1000 jobs in datatable grid to display
it but i have more then 1000 records to display.
What I want?
I want to display 500 records with grid and then 500 records.
I am not sure if there is any call back data-table plugin function available?
I need a dynamic way to load next 500
NOTE:
I am not willing to us this solution of scrolling
https://datatables.net/extensions/scroller/examples/initialisation/server-side_processing.html
You can user ajax data source:
please visit : https://datatables.net/examples/ajax/objects.html
Example PHP Script:
// function will process the ajax request
public function getMembers(Request $request) {
$draw = $request->get('draw');
$start = $request->get('start');
$length = $request->get('length');
$search = (isset($filter['value']))? $filter['value'] : false;
$total_members = 1000; // get your total no of data;
$members = $this->methodToGetMembers($start, $length); //supply start and length of the table data
$data = array(
'draw' => $draw,
'recordsTotal' => $total_members,
'recordsFiltered' => $total_members,
'data' => $members,
);
echo json_encode($data);
}
Example JavaScript :
$('#all-member-table').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
url: base_url+"ajax/members"
},
"columns": [
{ data: '1' },
{ data: '2' },
{ data: '3' },
{ data: '4' },
{ data: '5' },
]
} );
Example HTML:
<table id="all-member-table">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
<th>Column5</th>
</tr>
</thead>
</table>
I think above answer should be extended with search feature.
Update the answer;
$filter = $request->get('search');
$search = (isset($filter['value']))? $filter['value'] : false;
where('somecolumnonyourdb','like', '%'.$search.'%')
This works for me
You can use standard pagination:
$jobs = \App\Job::latest()->paginate(500);
Or create it manually.

Call to a member function getQuery() on array

Trying to do with datatables in laravel:
Error: Call to a member function getQuery() on array in laravel datatables
Here is Laravel Code:
Controller:
public function get_all_course_requests() {
$course_request = new CourseRequest();
$request_details = $course_request->get_all_course_requests();
$i = 0;
foreach ($request_details as $request) {
$request_details[$i]->sr_no = $request->id;
$request_details[$i]->l_fname = $request->l_fname;
$request_details[$i]->l_lname = $request->l_lname;
$request_details[$i]->l_mail = $request->l_mail;
$request_details[$i]->name = $request->name;
$request_details[$i]->request_date = $request->request_date;
$request_details[$i]->action = $request->id;
$i++;
}
return Datatables::of($request_details)
->filterColumn('l_fname', 'l_lname', 'name','course_name','request_date')
->make(true);
}
Model:
function get_all_course_requests($status='0') {
// DB::enableQueryLog();
$course_request = new CourseRequestModel;
$my_team_ids = $course_request->get_my_team_learner_ids();
return DB::table('course_request')
->select('login_details.l_fname','login_details.l_lname','login_details.l_mail','course_request.id','multilevel_course.name','course_request.request_date')
->whereIn('login_details.l_id', $my_team_ids)
->where('course_request.status', $status)
->join('login_details', 'login_details.l_id','=', 'course_request.user_id')
->join('multilevel_course', 'multilevel_course.id','=','course_request.course_id')
->whereIn('enrollment_policy',array('2','3') )
->get();
}
Here is JS Code:
$(function() {
$('#course_requests_table').DataTable({
processing: true,
serverSide: true,
ajax: BASE_URL + '/get_course_requests',
order: [],
columns: [
{data: "view", orderable: false,
render: function(data, type, row) {
return '<input type="checkbox" class="case" name="row_ids[]" value="' + data + '">';
}
},
{data: 'l_fname', name: 'l_fname'},
{data: 'l_lname', name: 'l_lname'},
{data: 'l_mail', name: 'l_mail'},
{data: 'name', name: 'name'},
{data: 'request_date', name: 'request_date'},
{data: 'action', orderable: false,
render: function(data, type, row) {
return '<a style="cursor:pointer" OnClick="delete_mail(' + data + ')"><i class="fa fa-trash"></i></a>';
}
}
]
});
});
Whats going wrong with code? and what to be done to solve this?
Solved:
Solution: converted array to Collection using collect()
$request_details = $course_request->get_all_course_requests();
$request_details= collect($request_details);
$i = 0;
foreach......

Resources