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