Laravel Datatables multiple actions edit / delete, delete displayed as text - laravel

I use datatables yajra/laravel-datatables package. I am almost there but the delete button is displays in text.
How can i display it as a button or link?
Data:
return Datatables::eloquent(Product::query())
->addColumn('action', function($row) {
return 'Edit';
})
->addColumn('delete', function ($row) {
return 'delete';
})
->make(true);
Js:
$(document).ready(function() {
oTable = $('#users').DataTable({
"processing": true,
"serverSide": true,
responsive: true,
columnDefs: [
{ responsivePriority: 1, targets: 1 },
{ responsivePriority: 2, targets: -2 },
{ responsivePriority: 3, targets: -1 }
],
"ajax": "http://admin/products",
"columns": [
<?php echo $string; ?>
{data: 'action', name: 'action', orderable: false, searchable: false},
{data: 'delete', name: 'delete', orderable: false, searchable: false}
],
Result:

I found the solution, ->rawColumns:
return Datatables::eloquent(Product::query())
->addColumn('action', function($row) {
return 'Edit';
})
->editColumn('delete', function ($row) {
return 'delete';
})
->rawColumns(['delete' => 'delete','action' => 'action'])
->make(true);

try adding class="btn btn-danger" to your delete anchor. just like your edit link.
return Datatables::eloquent(Product::query())
->addColumn('action', function($row) {
return 'Edit';
})
->addColumn('delete', function ($row) {
return 'delete';
})
->make(true);

Related

How to send parameters from datatable to controller Laravel

I have a datatable in my blade view Laravel, I user click the blue button it will open new page and show all task with same user_id as clicked before
I'm trying to pass user_id value to controller. I have do this following code
My routes
Route::get('/detail/{user_id}', [PageController::class, 'UserTask'])->name('user.task');
My datatable code in blade file
$(function() {
var user_id = $(this).data('user_id'); //have different value from each rows
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('user.task') }}" + '/' + user_id,
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
},
]
});
});
my controller
public function UserTask($user_id)
{
$data = Post::where('user_id', $user_id)->latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function ($row) {
$id = $row->id;
// $this->actionButton($row->id);
$btn = ' <span class="fas fa-info"></span>';
return $btn;
})->addColumn('target_selesai', function ($row) {
//...
})
->addColumn('progress', function ($row) {
//...
})->addColumn('status', function ($row) {
//...
})
->rawColumns(['action', 'progress', 'status'])
->make(true);
return view('detail');
}
But, it will return error Missing required parameter for [Route: user.task]
If I remove all the parameter {user_id}, from routes, ajax routes, and change the
public function UserTask($user_id)
{
$data = Post::where('user_id', $user_id)->latest()->get();
into
public function UserTask()
{
$data = Post::where('user_id', 1000000002)->latest()->get();
The program will works perfectly, how can I pass the user_id value from datatable to controller?
You cannot use "{{ route('user.task') }}" + '/' + user_id as route() function renders the route in the server while you're trying to change it in the client side. Send the user_id via as data with ajax and retrieve it using request()->get('user_id')

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);

Datatable not returning correct index while paginating

Laravel datatable using server side pagination, when doing any action on the datatable the indexing changes not in the correct order.
The controller code is below
return Datatables::of($newsletters)
->editColumn('created_at', function($row) {
return Carbon::parse($row->created_at)->format('d-m-Y');
})
->rawColumns(['created_at'])
->make(true);
}
JS code :
if($('#admin_news_letters_view').length > 0) {
$(document).ready(function () {
var i = 1;
$('#admin_news_letters_view').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('admin.news_letters.view') }}",
columns: [
{
"render": function (data, type, full, meta) {
return i++;
}
},
{data: 'name'},
{data: 'email'},
{data: 'created_at'},
]
});
});
}
Add an index colum in the controller.
Controller :
return Datatables::of($newsletters)
->addIndexColumn()
->editColumn('created_at', function($row) {
return Carbon::parse($row->created_at)->format('d-m-Y');
})
->rawColumns(['created_at'])
->make(true);
}
Js :
if($('#admin_news_letters_view').length > 0) {
$(document).ready(function () {
$('#admin_news_letters_view').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('admin.news_letters.view') }}",
columns: [
{
data: 'DT_RowIndex', name: 'DT_RowIndex'
},
{data: 'name'},
{data: 'email'},
{data: 'created_at'},
]
});
});
}

Laravel Datatable delete record with sweetalert dont working

I am using DataTables and Sweetalert but I have a problem, after confirmation in Sweetalert, nothing is deleted and I get 2 errors.
My controller(index & destroy):
public function index(Request $request)
{
if ($request->ajax()) {
$data = User::select('id','firstName')->get();
return Datatables::of($data)
->addColumn('action', 'partials.column')->rawColumns(['action'])
->make(true);
}
return view('admin.users.index');
}
public function destroy($id)
{
User::find($id)->delete();
return response()->json(['success'=>'Item deleted successfully.']);
}
Partials.column(blade)
<td><i class="bx bx-trash mr-1"></i> delete</td>
and js code
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var s, e = [];
0 < $("#users-list-datatable").length && (s = $("#users-list-datatable").DataTable({
order: [[0, "desc"]],
pageLength: 10,
processing: true,
serverSide: false,
language: {
'loadingRecords': ' ',
'processing': '<div class="spinner-border text-light spinner-border-lg"></div>'
},
ajax: "{{ route('admin.users.index')}}",
columns: [
{data: 'id', name: 'id'},
{data: 'firstName', name: 'firstName'},
{data: 'action', name: 'action', orderable: false, searchable: false},
],
}))
});
function deleteConfirmation(id) {
swal({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'DELETE',
url: "{{ route('admin.users.destroy','') }}"+'/'+id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
show this errors
DELETE http://127.0.0.1:8000/admin/users/ 405 (Method Not Allowed)
DELETE http://127.0.0.1:8000/admin/users/undefined 500 (Internal
Server Error)
The 405 means that your route isn't accepting that method. You need to check that the route /admin/users is able to use the delete method
Route::delete($uri, $callback);
You can see more on routing at the following page:
https://laravel.com/docs/7.x/routing
However you might also need to clear the route cache with
php artisan route:cache

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