Displaying Age to datatables laravel - laravel

i Have a function to showing Age on Model
This Model like this :
public function getAgeAttribute()
{
return Carbon::parse($this->attributes['tanggal_lahir'])->age;
}
and i parsing data on view ( without datatable) like
$users->age
but on datatable , not showing this data , just only Age is not showing
My Controller
public function indexDataTables_nonpns()
{
$users = User::with('master_agama','master_unit_kerja')->whereNotIn('nama',['admin'])->whereNotIn('roles_id',['2'])->get();
return Datatables::of($users)->addIndexColumn()
->addColumn('Nama', function ($users) {
return ''.$users->nama.'';
})
->rawColumns(['Nama' => 'Nama'])
->make(true);
}
My View
#push('scripts')
<script>
$(function() {
$('#table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: '{!! route('d_non_pns') !!}',
columns: [
{ data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false,searchable: false},
{ data: 'Nama', name: 'Nama'},
{ data: 'NIK', name: 'NIK'},
{ data: 'jenis_kelamin', name: 'jenis_kelamin'},
{ data: 'tempat_lahir', name: 'tempat_lahir'},
{ data: 'tanggal_lahir', name: 'tanggal_lahir'},
{ data: 'age', name: 'age'}, // i change this users.age ,but its didnt work
{ data: 'pendidikan', name: 'pendidikan'},
{ data: 'alamat', name: 'alamat'},
{ data: 'master_agama.agama', name: 'master_agama.agama'},
{ data: 'master_unit_kerja.unit_kerja', name: 'master_unit_kerja.unit_kerja'},
],
});
})
</script>
#endpush
someone can correct my fault ?

Related

status update in laravel

I have a admin login where the admin has to approve the student,I have used a toggle button for approval option, when clicked on the toggle button the value of status in database as to change from 1 to 0? How do I do this? Even if there are ways for it to work with normal buttons would also be helpful.Thank You.
<script type="text/javascript">
$(document).ready(function() {
$.noConflict();
fill_datatable();
function fill_datatable(collegeID = '') {
var table = $('.user_datatable1').DataTable({
order: [
[0, 'desc']
],
processing: true,
serverSide: true,
ajax: {
url: "{{ route('alumni.datatable1') }}",
data: {
collegeID: collegeID
}
},
columns: [{
data: 'id',
name: 'id'
},
{
data: 'name',
name: 'name'
},
{
data: 'status',
name: 'status',
mRender: function(data) {
return '<input data-id="{{$colleges->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Approved" data-off="Pending" {{ $colleges->status ? "checked" : "" }}>'
}
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
}
});
</script>
<script>
$(function() {
$(".toggle-class").change (function() {
var status = $(this).prop("checked")== true ? 0 : 1;
var id = $(this).data("id");
$.ajax({
type: "GET",
dataType: "json",
url: "/changeStatus",
data: {"status": status, "id": id},
success: function(data) {
console.log("Success")
}
});
});
});
</script>
Route
Route::get('changeStatus', [AdminAuthController::class, 'changeStatus'])->name('changeStatus');
Controller
public function changeStatus(Request $request,$regno)
{
$colleges = College::find($regno);
$colleges->status = $request->status;
$colleges->save();
return back();
}

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

How can I search for columns related to DataTables?

I have the following table:
DataTable
The field "placa" is a relation of the tables "maintenance" and "vehicles", when I try to search by means of a data from the field "placa" the datatable does not return results, how can I solve it?
Controller code:
public function mantenimientoData()
{
$mantenimiento = Mantenimiento::all();
return Datatables()
->eloquent(Mantenimiento::query())
->addColumn('placa', function($mantenimiento){
if ($mantenimiento->vehiculo_id) {
return $mantenimiento->vehiculos->placa;
} else {
return 'N/A';
}
})
->addColumn('btn', 'mantenimientos.actions')
->rawColumns(['btn'])
->make(true);
}
My view:
var table = $("#mantenimientos-table").DataTable({
serverSide: true,
pageLength: 10,
ajax: '{!! route('datatables.mantenimientos') !!}',
columns: [
{ data: 'nro_ficha', name: 'nro_ficha' },
{ data: 'placa', name: 'placa' },
{ data: 'fecha_ingreso', name: 'fecha_ingreso' },
{ data: 'fecha_egreso', name: 'fecha_egreso' },
{ data: 'estado', name: 'estado' },
{ data: 'valor_total', name: 'valor_total' },
{ data: 'btn', name: 'btn',orderable:false,serachable:false,sClass:'text-center' }
],
});
Maintenance Model:
class Mantenimiento extends Model
{
public function vehiculos()
{
return $this->belongsTo(Vehiculo::class, 'vehiculo_id');
}
}
and finally Vehicles Model:
class Vehiculo extends Model
{
public function mantenimientos()
{
return $this->hasMany(Mantenimiento::class);
}
}
Sorry for my bad English, but in Spanish I couldn't find help
I was able to fix it by applying a join as follows.
In my controller:
public function mantenimientoData()
{
$mantenimientos = Mantenimiento::join('vehiculos', 'vehiculos.id', '=', 'mantenimientos.vehiculo_id')
->select('vehiculos.id', 'vehiculos.placa', 'mantenimientos.nro_ficha',
'mantenimientos.fecha_ingreso', 'mantenimientos.fecha_egreso',
'mantenimientos.estado', 'mantenimientos.valor_total');
return Datatables::of($mantenimientos)
->addColumn('btn', 'mantenimientos.actions')
->rawColumns(['btn'])
->make(true);
}
Then in my view script:
var table = $("#mantenimientos-table").DataTable({
serverSide: true,
pageLength: 10,
ajax: '{!! route('datatables.mantenimientos') !!}',
columns: [
{ data: 'nro_ficha', name: 'mantenimientos.nro_ficha' },
{ data: 'placa', name: 'vehiculos.placa' },
{ data: 'fecha_ingreso', name: 'mantenimientos.fecha_ingreso' },
{ data: 'fecha_egreso', name: 'mantenimientos.fecha_egreso' },
{ data: 'estado', name: 'mantenimientos.estado' },
{ data: 'valor_total', name: 'mantenimientos.valor_total' },
{ data: 'btn', name: 'btn',orderable:false,serachable:false,sClass:'text-center' }
]
});
I share the solution that helped me in case someone else needs it

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

How to filter for just one customer with yajra datatables

I have a customers table with each record linking to a customer contact:
http://localhost/untdchem/public/home/customers/contacts/1809
When I click on the above link, I want to display all the contacts for customer 1809 only in a datatable. I am trying to pass the customer ID somehow so I can filter for that customer only. I can fill the table with all the contacts but i want to just load for that customer.
Routes:
//Customer Contacts
Route::get('home/customers/contacts', ['as' => 'customers.contacts', 'uses' => 'CustomerContactsController#index']);
Route::get('home/customers/contacts/data', ['as' => 'customers.contacts.data', 'uses' => 'CustomerContactsController#anyData']);
In my controller:
public function index()
{
// GET request to index
return view('pages.customer_contacts.index');
}
public function anyData()
{
$contacts = customer_contact::select(['CustContactFName','CustContactLName','CustContactCountryCode','CustContactExtension','CustContactPhone','CustContactEmail','CustContactType']);
return Datatables::of($contacts)->make(true);
}
In my view:
<script>
$(function() {
$('#customer-contacts-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('customers.contacts.data') !!}',
columns: [
{ data: 'CustContactFName', name: 'CustContactFName'},
{ data: 'CustContactLName', name: 'CustContactLName'},
{ data: 'CustContactCountryCode', name: 'CustContactCountryCode'},
{ data: 'CustContactExtension', name: 'CustContactExtension'},
{ data: 'CustContactPhone', name: 'CustContactPhone'},
{ data: 'CustContactEmail', name: 'CustContactEmail'},
{ data: 'CustContactType', name: 'CustContactType'}
//{ data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[0, "desc" ]]
});
});
</script>
Routes
Route::get('home/customers/contacts/{id}', ['as' => 'customers.contacts', 'uses' => 'CustomerContactsController#index']);
Route::get('home/customers/contacts/data/{id}', ['as' => 'customers.contacts.data', 'uses' => 'CustomerContactsController#anyData']);
Controller
I am assuming there is CustId field that identifies which customer the contact record is assigned to. If your structure is different, adjust accordingly.
public function index($id) {
// GET request to index
return view('pages.customer_contacts.index', compact('id'));
}
public function anyData($id){
$contacts = customer_contact::select([
'CustContactFName',
'CustContactLName',
'CustContactCountryCode',
'CustContactExtension',
'CustContactPhone',
'CustContactEmail',
'CustContactType'
])
->where('CustId', '=', $id);
return Datatables::of($contacts)->make(true);
}
JavaScript
Update the line with ajax option:
ajax: '{!! route('customers.contacts.data', ['id' => $id]) !!}',
The correct solution below:
public function index($CustID = null, Request $request)
{
if ($request->ajax()) {
$contacts = customer_contact::select(['CustContactFName','CustContactLName','CustContactCountryCode','CustContactExtension','CustContactPhone','CustContactEmail','CustContactType']);
if ($CustID) {
$contacts->where('CustID', $CustID);
}
//dd($contacts);
return Datatables::of($contacts)
->addColumn('action', function ($contacts) {
$links="";
$links.='Edit | ';
$links.='<a class="delete" href="'.url('home/customers/contacts/delete', [$contacts->CustID]).'">Delete</a> | ';
return $links;
})->make(true);
}
return view('pages.customer_contacts.index', compact('CustID'));
}
<script>
$(function() {
$('#customer-contacts-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('customers.contacts', $CustID) !!}',
columns: [
{ data: 'CustContactFName', name: 'CustContactFName'},
{ data: 'CustContactLName', name: 'CustContactLName'},
{ data: 'CustContactCountryCode', name: 'CustContactCountryCode'},
{ data: 'CustContactExtension', name: 'CustContactExtension'},
{ data: 'CustContactPhone', name: 'CustContactPhone'},
{ data: 'CustContactEmail', name: 'CustContactEmail'},
{ data: 'CustContactType', name: 'CustContactType'},
{ data: 'action', name: 'action', orderable: false, searchable: false}
],
order: [[0, "desc" ]]
});
});
</script>

Resources