Yarja Datatable Laravel - Null Date Value - laravel

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

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

Laravel Yajra Datatables sorting column with 3 set of values

I have implemented yajra datatables successfully for all reviews. One review can have 3 statuses: Approved, Pending, Blocked.
I have a column on datatables which is called Status and I want to sort column by status. By default the status is being ranged as per Approved and Declined but not for Pending.
Is there any way so I can sort this column by routing on this 3 statuses?
I'm sure that there is some editColumn or filterColumn method for my question but I'm not finding it any where.
Any way for #andrewjames pleasure I'm adding some non necessary code here:
public function indexDataService()
{
$reviews = DB::table('reviews')
->join('users', 'reviews.user_id', '=', 'users.id')
->join('statuses', 'reviews.status_id', '=', 'statuses.id')
->join('products', 'reviews.product_id', 'products.id')
->join('categories', 'reviews.category_id', 'categories.id')
->select([
'reviews.*',
'reviews.created_at AS created_at',
'statuses.title AS status',
DB::raw('CONCAT(users.first_name, " ", users.last_name) AS full_name'),
'products.title',
DB::raw('categories.title as category'),
])
->where('reviews.deleted_at', '=', NULL);
return Datatables::of($reviews)
->addColumn('action', function($review){
return view('admin/reviews/reviews_actions', compact('review'));
})
->editColumn('created_at', function ($review) {
$formatedDate = Carbon::createFromFormat('Y-m-d H:i:s', $review->created_at)->format('d-m-Y');
return $formatedDate;
})
->filterColumn('full_name', function ($query, $keyword) {
$keywords = trim($keyword);
$query->whereRaw("CONCAT(first_name, last_name) like ?", ["%{$keywords}%"]);
})
->filterColumn('category', function ($query, $keyword) {
$keywords = trim($keyword);
$query->whereRaw("categories.title like ?", ["%{$keywords}%"]);
})
->make(true);
}
On blade:
<script>
$('#category-reviews-table tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+'" />' );
} );
$(function() {
$('#category-reviews-table').DataTable({
"sDom":"ltipr",
processing: false,
serverSide: true,
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Italian.json"
},
ajax: '{{ route('admin.reviews.data') }}',
columnDefs: [
{"className": "dt-center", "targets": "_all"},
{
targets: [1],
render: function ( data, type, row ) {
return type === 'display' && data.length > 10 ?
data.substr( 0, 20 ) +'…' :
data;
}
}
],
columns: [
{ data: 'full_name', name: 'full_name' },
{ data: 'title', name: 'products.title' },
{ data: 'category', name: 'category'},
{ data: 'no_yes', name: 'reviews.no_yes', searchable:false },
{ data: 'status', name: 'status', searchable:false,
render: function( data, type, full, meta ) {
if (data === 'In attessa') {
return "<span class=\"badge badge-warning\">In attessa</span>";
} else if (data === 'Approvata') {
return "<span class=\"badge badge-success\">Approvata</span>";
} else if (data === 'Rifiutata') {
return "<span class=\"badge badge-danger\">Rifiutata</span>";
}
}
},
{ data: 'created_at', name: 'reviews.created_at', searchable:false },
{ data: 'action', name: 'action', orderable: false, searchable:false }
],
initComplete: function () {
this.api().columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
},
});
});
Can anyone give me some example how to achieve it?

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