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
Related
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.
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">
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',);
}
I have a problem on how to trim string in my datatable from a query where in used a raw query to get data from the database.
my query example is
public function data()
{
return DB::table('query_table')
->select([
DB::raw('query_table.data1 AS data1'),
DB::raw('query_table2.data2 AS data2'),
])
->join('query_table2','query_table2.query_table_id','=','query_table.id')
->where(['query_table.id' => 1])
->orderByDesc('query_table.data1')
->get();
}
from controller for my data table
public function dataDataTable()
{
$data = $this->query->data(); //query of data
return DataTables::of($data)
->addIndexColumn()
->make(true);
}
I am using datatables as view in laravel
#extends('layouts.main' , ['title' => trans('label.data.table')])
#include('includes.datatable_assets')
#push('after-styles')
#include('includes.custom_assets')
#endpush
#section('content')
<div class="card">
<div class="card-body">
<header class="card-header card-header-custom">
<h2 class="card-title" style="color: white" >{!! trans('label.table.header') !!}</h2>
</header>
<div class="" id="list-all">
<table class="display" id="templates-table">
<thead>
<tr>
<th>#lang('label.sn')</th>
<th>#lang('label.data1')</th>
<th>#lang('label.data2')</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
#endsection
#push('after-scripts')
<script type="text/javascript">
$('#templates-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('query.datatable.route') !!}',
type: 'get',
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false, width: '5%'},
{data: 'data1', name: 'data1', orderable: false, searchable: true, width: '65%'},
{data: 'data2', name: 'data2', orderable: false, searchable: true, width: '35%'},
],
</script>
#endpush
How do I trim data1 string so as can be seen with few characters in my datatable view ?
You can either do it in PHP or in Javascript:
Javascript:
$('#templates-table').DataTable({
...,
columnDefs: [{
targets: 1,
render: function (data, type, row) {
return type === 'display' && data.length > 50 ? data.substr(0, 50) + '…' : data;
}
}]
});
You can read more about it here.
PHP:
use Illuminate\Support\Str;
public function dataDataTable()
{
$data = $this->query->data(); // query of data
return DataTables::of($data)
->editColumn('data1', function ($data) {
return Str::limit($data->data1, 50);
})
->addIndexColumn()
->make(true);
}
If you don't have to show the user the full string I would use the PHP version, so your response does not get bloated.
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 :)