How to send parameters from datatable to controller Laravel - ajax

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

Related

Yarja Datatable Laravel - Null Date Value

I am having issue with handling a null values within a datatable.
In short I have a table with outstanding fees, which has a default null value in the table and is updated the Date paid when the person makes the payment.
This my ajax request in my controller
public function getTermFees(Request $request)
{
if($request->ajax()) {
$termid = TermMapping::latest()->value('id');
$termfees = TermFees::where('term_id', '=', $termid)->get();
return DataTables::of($termfees)
->addColumn('first_name', function($termfees) {
return $termfees->member->first_name;
})
->addColumn('last_name', function($termfees) {
return $termfees->member->last_name;
})
->addColumn('membership', function($termfees) {
return $termfees->member->membership_number;
})
->addColumn('action', function($row){
$btn = '<i class="fa fa-info"></i>';
return $btn;
})
->editColumn('date_paid', function($termfees){
return (is_null($termfees->date_paid) ? "-" : date('d/m/Y', strtotime($termfees->date_paid)));
})
->make(true);
}
}
This is my view
<script>
$(function() {
var table=$('#termfee-table').DataTable({
processing: true,
serverSide: true,
pageLength: 50,
ajax: '{{ route('getTermFees') }}',
columns: [
{ data: 'membership'},
{ data: 'first_name'},
{ data: 'last_name'},
{ data: 'status'},
{ data: 'date_paid', "defaultContent": "<i>-</i>"},
{ data: 'action', orderable: false, searchable: false}
],
});
})
</script>
Currently all fields in my Date Paid are showing "-" even if there is a date value in the table.
Any help would be great.
Thanks

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

Displaying Age to datatables 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 ?

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