Can't get ID from URL Laravel - 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);

Related

Unknown paramater name when calling data in datatable

When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Here is My controller
public function TeamTask(Request $request)
{
if ($request->ajax()) {
$data = Post::select(DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();
return Datatables::of($data)
->addIndexColumn()
->make(true);
}
return view('task.index',);
}
Here is 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: 'total',
name: 'total',
orderable: false,
},
{
data: 'finish',
name: 'finish'
},
]
});
});
</script>
When I call the data to view, an error appear said that "...Requested unknown paramater 'name'..."
Is something wrong in my controller or my view? thanks in advance
use this query
$data = DB::table('posts')->select('name', DB::raw('count(user_id) as total'))->selectRaw('SUM(status = "Finish") as finish')->groupBy('name')->get();

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: '-' },
],

Delete button in Yajra Datatables in Laravel 5.7.9

Hallo I have the MemberController with this action:
public function anyData()
{
$members = DB::table('members')
->select(['id','email','firstname','lastname','address','zip','city','phone','mobile','work','birthdate']);
return Datatables::of($members)
->addColumn('action', function ($id) {
return 'Edit
<button class="btn" data-remote="/member/' . $id->id . '">Delete</button>
'; })->make(true);
}
This is the JS Code to get the table with the datas:
<script type="text/javascript">
var table = $('#datatable-member').DataTable({
responsive: true,
"language": {
"url": "{{ asset('/plugins/datatables/lang').'/'.Config::get('app.locale').'.json'}}"
},
processing: true,
serverSide: true,
ajax: '{{ route('member') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'firstname', name: 'firstname' },
{ data: 'lastname', name: 'lastname' },
{ data: 'address', name: 'address' },
{ data: 'zip', name: 'zip' },
{ data: 'city', name: 'city' },
{ data: 'phone', name: 'phone' },
{ data: 'mobile', name: 'mobile' },
{ data: 'work', name: 'work' },
{ data: 'birthdate', name: 'birthdate' },
{data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[1, 'asc']]
}).$('.btn[data-remote]').on('click', function (e) {alert('test') })
;
</script>
The tables shows the data correctly, the edit link and delete button appears correctly but the action (at the moment only an alert) in the delete button is not working, when i click nothing happens.
I tryied also this on the javascript but nothing changed:
$('#datatable-member').DataTable().on('click', '.btn-delete[data-remote]', function (e) {alert('test') })
From Laravel framework for delete you need to have form validation by using X-CSRF Token. Try this to send a proper request for delete if you are using Laravel resource you can use below code, but make sure your datatable edit column are using the btn-delete class, as you are right now using the btn class.
<script type="text/javascript">
var table = $('#datatable-member').DataTable({
responsive: true,
"language": {
"url": "{{ asset('/plugins/datatables/lang').'/'.Config::get('app.locale').'.json'}}"
},
processing: true,
serverSide: true,
ajax: '{{ route('member') }}',
columns: [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: 'id', name: 'id' },
{ data: 'email', name: 'email' },
{ data: 'firstname', name: 'firstname' },
{ data: 'lastname', name: 'lastname' },
{ data: 'address', name: 'address' },
{ data: 'zip', name: 'zip' },
{ data: 'city', name: 'city' },
{ data: 'phone', name: 'phone' },
{ data: 'mobile', name: 'mobile' },
{ data: 'work', name: 'work' },
{ data: 'birthdate', name: 'birthdate' },
{data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[1, 'asc']]
});
$('#datatable-member').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
// confirm then
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
}).always(function (data) {
$('#datatable-member').DataTable().draw(false);
});
});

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)

How to add the CSV,PDF buttons for a datatable using the Laravel Yajra plugin?

I am creating a datatable using Laravel's Yajra plugin. I am using the query builder form.(Like this Click here)
I wanna add buttons CSV,PDF to the datatable.
I know as per the documentation it can be done Like this
The problem is I have already done using query builder. Now I cannot change my code.
Kindly help me.
My jquery code is as follows:
<script type="text/javascript">
$(document).ready(function(){
$('body').addClass('sidebar-collapse');
var cat = "{{$cat}}";
$('#unreconcil_datatable').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('get_datatable',array('cat'=>$cat)) !!}',
columns: [
{ data: 'unrelines_uniq_num', name: 'unrelines_uniq_num' },
{ data: 'unrelines_bank_accno', name: 'unrelines_bank_accno' },
{ data:'unrelines_rficreated',name:'unrelines_rficreated'},
{ data: 'unrelines_roicreated', name: 'unrelines_roicreated' },
{ data: 'unrelines_bank_name', name: 'unrelines_bank_name' },
{ data: 'unrelines_line_number', name: 'unrelines_line_number' },
{ data: 'unrelines_state_date', name: 'unrelines_state_date' },
{ data: 'unrelines_trans_date', name: 'unrelines_trans_date' },
{ data: 'unrelines_trans_amount', name: 'unrelines_trans_amount' },
{ data: 'unrelines_unrec_amt', name: 'unrelines_unrec_amt' },
{ data: 'unrelines_desc', name: 'unrelines_desc' },
{ data: 'unrelines_variance', name: 'unrelines_variance' },
{ data: 'unrelines_cstatus', name: 'unrelines_cstatus' },
{ data: 'unrelines_assigned', name: 'unrelines_assigned' },
{ data: 'unrelines_created_date', name: 'unrelines_created_date' },
{data: 'tat', name: 'tat', orderable: false, searchable: false},
{data: 'action', name: 'action', orderable: false, searchable: false}
]
});
});
</script>
My controller method is as follows:
public function getdatatable($cat){
$list = AvailableStatementLines::select([DB::raw(" '$cat' AS cat"),'unrelines_id','unrelines_uniq_num','unrelines_bank_accno','unrelines_rficreated','unrelines_roicreated','unrelines_bank_name','unrelines_line_number','unrelines_state_date','unrelines_trans_date','unrelines_trans_amount','unrelines_unrec_amt','unrelines_desc','unrelines_variance','unrelines_cstatus','unrelines_assigned','unrelines_created_date','unrelines_trans_type','unrelines_currency','unrelines_created_by_name','unrelines_ustatus',DB::raw("IF(unrelines_cstatus='closed', '',
ROUND(ABS(TIMESTAMPDIFF(MINUTE, date(unrelines_lastupdate), curdate()))/1440 - ABS(DATEDIFF(ADDDATE(curdate(), INTERVAL 1 -DAYOFWEEK(curdate()) DAY), ADDDATE(date(unrelines_lastupdate), INTERVAL 1 -DAYOFWEEK(date(unrelines_lastupdate)) DAY))) / 7 * 2 - (DAYOFWEEK(IF(date(unrelines_lastupdate) < curdate(), date(unrelines_lastupdate), curdate())) = 1) - (DAYOFWEEK(IF(date(unrelines_lastupdate) > curdate(), date(unrelines_lastupdate), curdate())) = 7),0)
) AS tat")])->where('unrelines_ucountry',Session::get('country'))->where('unrelines_display',1);
switch($cat){
case 'rfi':
$list1 = $list->where('unrelines_cstatus','Assigned');
break;
case 'roi':
$list1 = $list->where('unrelines_cstatus','Solution Provided');
break;
case 'closed':
$list1 = $list->where('unrelines_cstatus','Closed');
break;
default:
$list1 = $list->whereNotIn('unrelines_cstatus',['Closed','Assigned','Solution Provided']);
break;
}
return Datatables::of($list1)
->addColumn('unrelines_uniq_num',function($list1){
return "<input type='checkbox' class='uniqnums' name='uniquenum[]' value='".$list1->unrelines_id."'>".$list1->unrelines_uniq_num;
})
->addColumn('action',function($list1){
return "<button type='button' class='btn btn-xs btn-info viewLine' category=".$list1->cat." unrelines=".$list1->unrelines_id.">View</button>";
})
->setRowClass(function ($list1) {
return $list1->tat > 7 ? 'orange' : ($list1->tat > 5 ? 'red' : ' ');
})
->make(true);
}
You should apply this method in your controller.
public function html()
{
return $this->builder()
->columns([
'id',
'name',
'email',
'created_at',
'updated_at',
])
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['csv', 'excel', 'pdf', 'print', 'reset', 'reload'],
]);
}

Resources