Laravel DataTables search in column generated with DB::raw - laravel-5

I have the following issue in Laravel DataTables (yajra/laravel-datatables
):
I can't search (filter) in a column generated with DB::Raw.
Also I can't search with Global search function.
In my Laravel Controller:
$inputs = Input_::join('companies', 'companies.id', '=', 'inputs.company_id')
->leftjoin('inputs_details', 'inputs_details.input_id', '=', 'inputs.id')
->select(array('inputs.id as id',
'inputs.created_at as created_at',
'inputs.updated_at as updated_at',
'inputs.input_at as input_at',
'companies.name',
'inputs.documents as documents',
DB::raw("SUM(inputs_details.quantity*inputs_details.price_input*(1+inputs_details.VAT/100)) as input_total")
))
->groupBy('inputs.id')
->orderBy('inputs.input_at', 'DESC');
return Datatables::of($inputs)
->remove_column('id')
->make(true);
In my View:
$('#inputs-table').DataTable({
processing : true,
serverSide : true,
ajax: '{{ URL::to('employee/inputs/data/') }}',
columns: [
{data: 'created_at', name: 'inputs.created_at', orderable: false},
{data: 'updated_at', name: 'inputs.updated_at', orderable: false},
{data: 'input_at', name: 'inputs.input_at', orderable: false},
{data: 'name', name: 'companies.name', orderable: false},
{data: 'documents', name: 'inputs.documents', orderable: false},
{data: 'input_total', name: 'input_total', orderable: false, searchable: true},
{data: 'reports', name: 'reports', orderable: false, searchable: false},
{data: 'actions', name: 'actions', orderable: false, searchable: false}
],
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement("input");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? val : '', true, false).draw();
});
});
} });

You have to put the filterColumn action in your datatable.
$inputs = Input_::join('companies', 'companies.id', '=', 'inputs.company_id')
->leftjoin('inputs_details', 'inputs_details.input_id', '=', 'inputs.id')
->select(array('inputs.id as id',
'inputs.created_at as created_at',
'inputs.updated_at as updated_at',
'inputs.input_at as input_at',
'companies.name',
'inputs.documents as documents',
DB::raw("SUM(inputs_details.quantity*inputs_details.price_input*(1+inputs_details.VAT/100)) as input_total")
))
->groupBy('inputs.id')
->orderBy('inputs.input_at', 'DESC');
return Datatables::of($inputs)
->remove_column('id')
->filterColumn('input_total', function($query, $keyword) {
$query->whereRaw("SUM(inputs_details.quantity*inputs_details.price_input*(1+inputs_details.VAT/100)) = ?", $keyword);
})
->make(true);

Related

Can't get ID from URL Laravel

I have a datatable view that shows some post from user, I want to create a datatable with a button that can show all user post. But, when moving from all post lists to user post lists I cant get user_id from the URL.
I want to get the user_id using $request->route.
Here is my controller:-
public function index(Request $request)
{
if ($request->ajax()) {
$request->route('detail');
$data = Post::where('user_id', $this->route('detail'))->latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('detail');
}
Here is my route:-
Route::resource('detail', DetailController::class);
datatable code
var table = $('.data-table').DataTable({
paging: true,
info: true,
autoWidth: false,
responsive: true,
columnDefs: [{
"targets": [0, 2, 3, 4, 5, 6], // your case first column
"className": "text-center",
},
],
language: {
paginate: {
next: '<span class="fas fa-arrow-right"></span>', // or '→'
previous: '<span class="fas fa-arrow-left"></span>' // or '←'
}
},
oLanguage: {
"oPaginate": {
next: '→', // or '→'
previous: '←' // or '←'
},
"sLengthMenu": "Tampilkan _MENU_ Item",
"sEmptyTable": "Tidak ada data",
"sInfoEmpty": "Tidak ditemukan",
"sLoadingRecords": "Sedang memproses - loading...",
"sInfo": "Menampilkan _START_ - _END_ dari _TOTAL_ Item",
"sSearch": "Cari:",
},
processing: true,
serverSide: true,
ajax: "{{ route('detail.index') }}",
columns: [{
data: 'DT_RowIndex',
name: 'DT_RowIndex',
orderable: false,
searchable: false,
},
{
data: 'title',
name: 'title',
orderable: false,
},
{
data: 'content',
name: 'content',
orderable: false,
visible: false,
},
{
data: 'progress',
name: 'progress'
},
{
data: 'status',
name: 'status'
},
{
data: 'target_selesai',
name: 'target_selesai'
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
If I change the $this->route('detail') into user_id value, the program will work as expected. Is there something wrong with my code? thanks in advance
Change this:-
$this->route('detail')
To:-
$request->get('details')
And your ajax method should be like this:
"ajax": {
'type': 'POST',
'url': '{{ route('detail.index') }}',
'data': {
detilas: 'your id',
},
}
your roure:
Route::post('detail', DetailController::class);

laravel datatables search in addColumn

I use laravel/datatables to list data.
I manipulated my datalist with addColumn function.
However I am not able to use search in view for added columns.
Because search is working according to database rows.
Datatables works fine but in the view search area is not working. Because there isnt any fullname row in database table.
Here you can find my codes (I want to search for fullname but I can't)
Order Model
public function getFullname()
{
return json_decode($this->getAttribute('delivery_adress'))->fullname;
}
OrderController.php
if ($request->ajax()) {
return datatables()->of(Order::query())
->addColumn('fullname', function (Order $order) {
return $order->getFullname();
})->addColumn('city', function (Order $order) {
return $order->getCity();
})->addColumn('product_id', function (Order $order) {
return $order->product->title;
})->make(true);
}
Orders Blade / Datatables code
"pageLength": 10,
processing: true,
serverSide: true,
ajax: 'orders',
columns: [
{ data: 'id', name: 'id'},
{ data: 'fullname', name: 'fullname', defaultContent: '-' , orderable: false },
{ data: 'city', name: 'city', defaultContent: '-', orderable: false },
{ data: 'product_id', name: 'product_id', className: 'd-none d-sm-table-cell', defaultContent: '-' },
{ data: 'totalPrice', name: 'totalPrice', className: 'd-none d-sm-table-cell', defaultContent: '-' },
],
edit:
Finally, I found solution
{data: 'added_column', name: 'actual_column_name'}
https://github.com/yajra/laravel-datatables/issues/139#issuecomment-275326787
Finally, I found solution
{data: 'added_column', name: 'actual_column_name'}
https://github.com/yajra/laravel-datatables/issues/139#issuecomment-275326787
Make sure to have relationship into Order model like this:
public function user()
{
return $this->belongsTo('App\User');
}
Try to update like this :
...
->addColumn('fullname', function (Order $order) {
return $order->user->fullname;
})
...
change status
serverSide : false
"pageLength": 10,
processing: true,
serverSide: false,
ajax: 'orders',
columns: [
{ data: 'id', name: 'id'},
{ data: 'fullname', name: 'fullname', defaultContent: '-' , orderable: false },
{ data: 'city', name: 'city', defaultContent: '-', orderable: false },
{ data: 'product_id', name: 'product_id', className: 'd-none d-sm-table-cell', defaultContent: '-' },
{ data: 'totalPrice', name: 'totalPrice', className: 'd-none d-sm-table-cell', defaultContent: '-' },
],

Laravel: How can i sorting data using ajax in datatables?

I am getting data of invoice table but i want to sort data in desc
This is my code:
var oTable = $('#ks-datatable').DataTable({
'processing': false,
'serverSide': true,
"searching": false,
/*"bLengthChange": false,*/
'ajax': '{{route('invoice.index')}}',
columns: [
{data: 'id', name: 'id'},
{data: 'client_name', name: 'client_name'},
{data: 'invoice_number', name: 'invoice_number'},
{data: 'date', name: 'date'},
{data: 'created_at', name: 'created_at'},
{data: 'amount', name: 'amount'},
{data: 'action', name: 'action', searchable: false},
]
});
use order in datatable :
"ordering":'true'
"order": [columnNumber, 'orderType'],
Example
....
"ordering":'true'
"order": [0, 'desc'],
Your code will be:
var oTable = $('#ks-datatable').DataTable({
'processing': false,
'serverSide': true,
"searching": false,
/*"bLengthChange": false,*/
'ajax': '{{route('invoice.index')}}',
"ordering":'true',
"order": [0, 'desc'],
columns: [
{data: 'id', name: 'id'},
{data: 'client_name', name: 'client_name'},
{data: 'invoice_number', name: 'invoice_number'},
{data: 'date', name: 'date'},
{data: 'created_at', name: 'created_at'},
{data: 'amount', name: 'amount'},
{data: 'action', name: 'action', searchable: false},
]
});

How to use HasManyThrough Relation in laravel datatable

I have three tables i am able to use relation between 2 tables easily. But when i am trying to access values from third table i mean trying to use hasManyThrough relation it is showing me always error. Do you have any idea how i can get value of third table column using middle table relation with first and last table.
System details
Linux
PHP 7
Laravel 5.3
Laravel-Datatables Latest Version
$('#mms-table').DataTable({
processing : true,
serverSide: true,
lengthMenu: [10,25,50,100],
order: [[1,'desc']],
ajax: '{!! url(LaravelLocalization::getCurrentLocale()."/admin/contact-management/contact-data") !!}',
columns: [
{ data: 'merchant.bank.name', name: 'merchant.bank_id', orderable: true },
{ data: 'merchant.merchant_id', name: 'merchant.merchant_id', orderable: true },
{ data: 'merchant.merchant_name', name: 'merchant.merchant_name', orderable: true },
{ data: 'contact.name', name: 'contact.name', orderable: true },
{ data: 'contact.email', name: 'contact.email', orderable: true },
{ data: 'city', name: 'city', orderable: true },
{ data: 'agent.name', name: 'agent.name', orderable: true },
{ data: 'action', name: 'action', orderable: false, searchable: false},
],
dom: 'Blfrptip',
buttons: [
{
extend: 'colvis',text: 'Show/Hide Columns'
}
],
oLanguage: {
sProcessing: "<img height='80' width='80' src='{{ url('public/images/loading.gif') }}' alt='loader'/>"
},
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();
});
});
}
});

How to make a date/time count like facebook (3days ago, etc)

I'm a newbie in php, and offcourse I'm a newbie in laravel. Anyway, 've got a problem. In some documentations, people uses "diffForHuman". Unfortunately I always get error 500 when I use it. I want to do a count of date/time like facebook, ex : "3days ago", etc.
this is my controller :
public function show(Request $request)
{
if($request->ajax()){
$searchs = $request->get('search');
$search = $searchs['value'];
\DB::statement(\DB::raw('set #nomor = 0'));
$index = DB::table('tb_jabatan_karyawan')
->leftJoin('tb_jabatan','tb_jabatan.id','=','tb_jabatan_karyawan.id_jabatan')
->leftJoin('tb_karyawan','tb_karyawan.id','=','tb_jabatan_karyawan.id_karyawan')
->select([
\DB::raw('#nomor := #nomor + 1 as no'),
'tb_jabatan_karyawan.id as id',
'tb_jabatan_karyawan.id_karyawan as id_karyawan',
'tb_jabatan_karyawan.id_jabatan as id_jabatan',
'tb_karyawan.nama as nama',
'tb_karyawan.status_karyawan as status',
'tb_jabatan.nama_jabatan as jabatan',
'tb_karyawan.tgl_masuk as lama'
]);
//dd(Carbon::parse($index->lama)->diffForHumans());
return Datatables::of($index)
->edit_column('no', function($index){
return '<center>'.$index->no.'</center>';
})
->edit_column('nama', function($index){
return ucwords($index->nama);
})
->edit_column('status', function($index){
return ucwords($index->status);
})
->editColumn('lama', function ($index) {
return $index->lama->diffForHumans();
})
->filter(function ($query) use ($request){
if ($request->get('search')['value']){
$query->where('nama', 'like', "%{$request->get('search')['value']}%");
}
})
->addColumn('action', function($index){
$tag = "<center><a class='btn btn-info btn-xs' onclick=atur('".$index->id_karyawan."','".$index->id_jabatan."')><i class='fa fa-pencil'></i> Proses</a></center>";
return $tag;
})
->make(true);
}
}
and this is my datatable :
function getData(){
table = $('#table').DataTable({
dom: "lBfrtip",
processing: true,
serverSide: true,
destroy: true,
bFilter:true,
searching: true,
order: [],
ajax: base_adm+'kelola/pengunduran-karyawan/show',
columns: [
{data: 'no', name: 'no', orderable: true, searchable: false},
{data: 'nama', name: 'nama', orderable: true, searchable: true},
{data: 'status', name: 'status', orderable: true, searchable: false},
{data: 'jabatan', name: 'jabatan', orderable: true, searchable: false},
{data: 'lama', name: 'lama', orderable: true, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false},
],
"language": {
"lengthMenu": " _MENU_ Baris",
"zeroRecords": "Data Tidak Tersedia",
"info": "Halaman _PAGE_ Dari _PAGES_",
"infoEmpty": "Data Tidak Tersedia",
"infoFiltered": "(Hasil penyaringan dari _MAX_ total data)",
"sSearch": "Pencarian ",
"oPaginate": {
"sNext" : "Selanjutnya",
"sPrevious" : "Sebelumnya",
},
},
});
}
I hope someone will help me to fix this. thank's anyway
Well, your $index->lama needs to be a Carbon object. So try
\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $index->lama)->diffForHumans(); (assuming dates on your database stored in "Y-m-d H:i:s" format)

Resources