Can't get user_id value Laravel Query - laravel

I can't call user_id in my view page using datatable, when I change the select('name') into select('user_id') or select('*') it also show error DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Whats wrong with my code? thanks in advance
I have a controller contain following code
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = DB::table('posts')->select('name')->selectraw('count(user_id) as total')->selectRaw('SUM(status = "Done") as done')->where('div', Auth::user()->div)->groupBy('name')->get();
return Datatables::of($data)
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('task.teamTask',);
}
my view
<script type="text/javascript">
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('team.task') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'name',
name: 'name',
orderable: false,
},
{
data: 'user_id',
name: 'user_id',
orderable: false,
},
{
data: 'total',
name: 'total',
orderable: false,
},
{
data: 'done',
name: 'done'
},
{
data: 'action',
name: 'action'
},
]
});
});
</script>
I can't call user_id in my view page using datatable, when I change the select('name') into select('user_id') or select('*') it also show error DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Whats wrong with my code? thanks in advance

Add ->groupBy('user_id') in your query, this should fix your problem

Try this.
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = DB::table('posts')->select('name','user_id')->selectraw('count(user_id) as total')->selectRaw('SUM(status = "Done") as done')->where('div', Auth::user()->div)->groupBy('name')->get();
return Datatables::of($data)
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('task.teamTask',);
}

Related

Yajra multi search filters

I am trying to assign a custom search box for each column of the table as shown in this example.
https://datatables.yajrabox.com/eloquent/multi-filter-select
But the code given for this was so confusing. I am not getting any idea how to use that code to achieve this.
Here is my code.
CONTROLLER FUNCTION
function leadManage(Request $request){
$lead_id = $request->get('id');
echo $lead_id;
if ($request->ajax() && $request->draw) {
$data = lead::select('leads.id', 'leads.fname', 'leads.lname', 'leads.phone', 'leads.email', 'leads.created_at', 'lead_status_lists.status_name', 'users.fname as user_fname', 'users.lname as user_lname');
$data = $data->join('users', 'leads.assigned_to', '=', 'users.id');
$data = $data->orderBy('leads.id', 'DESC');
$data = $data->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('date', function($row){
$date = date('d M Y', strtotime($row->created_at));
return $date;
})
->addColumn('action', function($row){
$btn = '<i class="fa fa-pencil font-14"></i>
<button class="btn btn-danger btn-sm" data-toggle="tooltip" data-original-title="Delete" onclick="return deletelead_conf('.$row->id.')"><i class="fa fa-trash font-14"></i></button>';
return $btn;
})
->rawColumns(['name','user_name','date','action'])
->make(true);
}
return view('admin.lead_manage');
}
View File script
$(document).ready(function() {
$('.dataTable').DataTable( {
processing: true,
serverSide: true,
ajax: "{{ route('lead.index') }}",
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false },
{data: 'name', name: 'name'},
{data: 'phone', name: 'phone'},
{data: 'email', name: 'email'},
{data: 'course_name', name: 'course_name'},
{data: 'user_name', name: 'user_name'},
{data: 'status_name', name: 'status_name'},
{data: 'date', name: 'date'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
I tried to add additional script from given url but it make table body empty and no error. Here is script from given url which I tried to add.
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement("input");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}
But I am not getting any idea how to use those controller function (from given url) in my written code.

My laravel Yajra datatable does not render. It says invalid json response. However I can not read the error since the response is empty

Hello I have the following controller method to return data to my datatable in Laravel,
Controller Method
public function get(Request $request) {
return Datatables::of(AppUser::all())
->addColumn('status', function ($user) {
if ($user->status == 1) {
return '<span class="label label-success">Active</span>';
} else {
return '<span class="label label-danger">Inactive</span>';
}
})
->addColumn('actions', function ($user) {
return view('backend.appuser.actionButton', compact('user'))->render();
})
->make(true);
}
Then in the view I render the datatable, I have the following code.
<table id="users-table" class="table table-condensed table-hover">
<thead>
<tr>
<th>Username</th>
<th>NIC</th>
<th>Mobile</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
Inside my script tag I have the below code
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route("admin.app-access.user.get") }}',
type: 'get',
data: {status: 1, trashed: false}
},
columns: [
{data: 'email', name: 'email'},
{data: 'nic', name: 'nic'},
{data: 'mobile', name: 'mobile'},
{data: 'status', name: 'status'},
{data: 'actions', name: 'actions'}
],
pageLength:25,
lengthMenu:[[10,25,50,100,-1],[10,25,50,100,"All"]],
order: [ [ 0, "desc" ] ],
dom: "lBfrtip",
buttons:
[
{extend: 'excel', footer: true, title: 'User Details'},
{extend: 'pdf', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'},
{extend: 'print', footer: true, title: 'User Details', orientation: 'landscape', pageSize: 'LEGAL'}
],
searchDelay: 500
});
});
The Error
When I go to the index page that the datatable is loaded, it says,
DataTables warning: table id=users-table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
What I tried
I tried making a little syntax error in the above controller method to see if the application crashes. If the application crashes, it means that the request sent from the datatable must have hit my controller method. (App actually crashed, so the request from the datatable is coming to my controller method.)
I went to the network tab in my developer tools and inspected the response for the request sent from the data-table. The response is empty. It just shows three empty lines. Since the response is empty, I can not figure out what the error is.
Below picture shows the response I got.
(I am using Laravel 5.4)
I have added rawColumns before the ->make(true) will you try with this solution once?
It should work I guess so!
So here your will looks like...
public function get(Request $request) {
return Datatables::of(AppUser::all())
->addColumn('status', function ($user) {
if ($user->status == 1) {
return '<span class="label label-success">Active</span>';
} else {
return '<span class="label label-danger">Inactive</span>';
}
})
->addColumn('actions', function ($user) {
return view('backend.appuser.actionButton', compact('user'))->render();
})
->rawColumns(['status', 'actions'])
->make(true);
}

Load DataTable where select in Laravel 8 with yajra datatables

I need to load a DataTable where the input value equals the value in the database. I try to use this function but not work correctly.
Controller
public function getit(Request $request)
{
$shp_no = $request->shp_no_for_it;
$data = Item::select('*')->where('shp_no_for_it', $shp_no)->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = '<a href="javascript:void(0)"
class="edit btn btn-primary btn-sm">View</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
Script
$('#search_button').click(function(){
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('getit') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
});
Input
<input type="title" class="form-control" id="shp_no_for_it" name="shp_no_for_it">
Route
Route::get('getit', [ItemController::class, 'getit'])->name('getit');
Look like you have not passed data in ajax. So first create a function to datatable
function itemDataTable(param={}){
dataTable = $('#itemTable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('getit') }}",
type: 'get',
headers: { 'content-type': 'application/x-www-form-urlencoded', 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: param,
},
columns: [
{data: 'id', name: 'id'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
return dataTable;
}
Then on page load call data table
$(function () {
itemDataTable();
});
and on click search button
$('#search_button').click(function(){
var param={
shp_no_for_it:$('#shp_no_for_it').val();
}
itemDataTable(param)
});
and in controller if you are using server side processing then no need to call get() .But add following
processing: true,
serverSide: true,
and in controller
public function getit(Request $request)
{
$shp_no = $request->shp_no_for_it;
$data = Item::select('*') ->where('shp_no_for_it', $shp_no);
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'View';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
and in html table
<table class="table table-bordered data-table col-md-12" id="itemTable">

Laravel Yajra DataTable Column Sorting not proper working

Laravel Yajra DataTable Column Sorting not proper working. If I use ->get() function in Query then DataTable sorting works fine. But I don't want to use get() function because If I have more than 100 000 records then it takes too much time so I don't want to use get() in query
here is my controllers code
$deals = Deal::orderBy('updated_at', 'desc');
$searcharray = array();
parse_str($request->fromValues,$searcharray);
if(isset($searcharray) && !empty($searcharray)){
if($searcharray['filtertype'] !=''){
$deals->where("deal_isApproved",'=',$searcharray['filtertype']);
}
}
$detail_data = $deals;
// print_r($deals);
return Datatables::of($detail_data)
->addColumn('action', function ($data) {
$btn .= '<a class="dropdown-item" href="'.route('admin.deals.edit',$data->id).'" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-edit text-primary"></i> Edit</a>';
$btn .= '<a deal_id="'.$data->id.'" class="dropdown-item deleteDeal" href="#" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-trash-alt text-danger"></i> Delete</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
here is my datatable initialize in blade file
var dataTable = $('#example_laravel').DataTable({
//lengthMenu: getPageLengthDatatable(),
processing: true,
serverSide: true,
order: [],
searchDelay: 500,
"scrollX": "auto",
// responsive: true,
// // "responsive": true,
// "lengthChange": false,
// "autoWidth": false,
ajax: {
url: '{{ route("admin.deals.filter")}}',
type: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (data) {
data.fromValues = $("#filterdealtype").serialize();
},
},
columns: [
{data: 'SrNo', //try with data: 'SrNo' OR data: 'id',
render: function (data, type, row, meta) {
// return meta.row + meta.settings._iDisplayStart + 1;
return meta.row + 1;
}, searchable: false, sortable: false
},
{data: 'deal_title', name: 'deal_title'},
{data: 'deal_desc',
render: function (data, type, row, meta) {
var data = decodeHTMLEntities(data);
var data = data.replaceAll("href=\"","href=\"http://");
return '<div style="width: 340px; word-wrap: break-word;">'+data+'</div>';
},
},
{data: 'deal_price', name: 'deal_price'},
{data: 'deal_retail_price', name: 'deal_retail_price'},
{data: 'deal_percent_off', name: 'deal_percent_off'},
{data: 'deal_img',
render: function (data, type, row, meta) {
if(data){
return '<img id="myImg" src="{{ asset('') }}'+data+'" height="100px" width="100px">';
}else{
return '';
}
}
},
{data: 'deal_start_date', name: 'deal_start_date'},
{data: 'action', name: 'action', searchable: false, sortable: false},
],
});
output I get be like below image
I solve another problem related to sorting... I share answer of this for helping to other people,
Actually when I define orderby in controller than when I click on Datatable Column for sorting then it was not sorting, because when we click on column than it pass two times different different orderby field so its not works,
Solution of Problem
$deals = Deal::select('*');
if($request->order ==null){
$deals->orderBy('created_at', 'desc');
}
& Another problem about wrong sequence of sorting data issue faced because of wrong datatype in DataBase table...
So, Please also verify Datatype of Database
I hope its helps to you...
& thanks to you #ibrahim-dogan this guy for answer me about wrong Datatype...
thank you

My Datatable on Laravel 5.3 sometime error

I've been using Datatable on my Laravel project, but sometime when I refresh the page, it works and sometime it doesnt
This is my script on view
#section('script')
<script type="text/javascript">
$(function () {
var oTable = $('#tabel-stok').DataTable({
processing: true,
serverSide: true,
order: [[ 0 ,"desc"]],
ajax: {
url: '{{ url("data-stok") }}'
},
columns: [
{data: 'updated_at', name: 'updated_at'},
{data: 'nama_produk', name: 'nama_produk'},
{data: 'harga_satuan', name: 'harga_satuan'},
{data: 'jumlah_stok', name: 'jumlah_stok'},
{data: 'tambah', name: 'tambah', orderable: false, searchable: false},
{data: 'edit', name: 'edit', orderable: false, searchable: false}
],
});
});
</script>
#endsection
This is my controller
public function index()
{
return view('transaksi-masuk.transaksi-masuk');
}
public function dataStok()
{
$stok = Produk::all();
return Datatables::of($stok)
->addColumn('tambah', function ($stok) {
return '<span class="label label-primary">TAMBAH</span>';
})
->addColumn('edit', function ($stok) {
return '<span class="label label-warning">EDIT</span>';
})
->make(true);
}
And this is the error message
DataTables warning: table id=tabel-stok - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Is there any solution for this? Thank you
It works now. I tried to remove addColumn from controller and edit my script like this
columns: [
{data: 'updated_at', name: 'updated_at'},
{data: 'nama_produk', name: 'nama_produk'},
{data: 'harga_satuan', name: 'harga_satuan'},
{data: 'jumlah_stok', name: 'jumlah_stok'},
{
name: '',
data: null,
sortable: false,
searchable: false,
render: function (data) {
var actions = '';
actions += '<span class="label label-primary">TAMBAH</span>';
actions += '<span class="label label-warning">EDIT</span>';
return actions.replace(/:id/g, data.id_produk);
}
}
Thank you for helping me :)

Resources