status update in laravel - 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();
}

Related

fetch data on dropdown change event from database to dataTables using ajax in Codeigniter 4

fetch data from database to datatables using ajax on dropdown change.
controller and model is working fine when use simple dropdown change event using ajax, but when try to fetch data to dataTables then show an error
no data available
Controller:
public function getStudents()
{
$model = new ModelAjax();
$sessionid = $this->request->getVar('sessionid');
$classid = $this->request->getVar('classid');
$data = $model->getStudents($sessionid,$classid);
echo json_encode($data);
}
Model:
public function getStudents($sessionid,$classid)
{
$model = new ModelStudent();
$array = ['sessionid' => $sessionid, 'classid' => $classid];
$data = $model->select('tblstudent.studentname,tblstudent.fathername, tblstudent.rollno ,tblstudent.mobile1')
->join('tblenrollment','tblstudent.id = tblenrollment.studentid','left')
->where($array)
->findAll();
return $data;
}
Script:
$("#classid").change(function(){
var sessionid = $("#sessionid").val();
var classid = $(this).val();
$('#example').DataTable({
ajax: {
url: "<?php echo site_url('Ajax/getStudents'); ?>",
type: "POST",
data: function(d){
d.sessionid = $("#sessionid").val();
d.classid = $("#classid").val();
}
},
dom: 'Bfrtip',
iDisplayLength: 15,
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'pageLength'
],
search: true
});
});
Finally succeeded to do it:
$("#classid").change(function(){
var sessionid = $("#sessionid").val();
var classid = $(this).val();
$.ajax({
url : "<?php echo site_url('Ajax/getStudents'); ?>",
method : "POST",
data : {sessionid: sessionid, classid: classid},
async : true,
dataType : 'json',
success: function(data)
{
$('#example').DataTable({
destroy: true,
data : data,
columns: [
{ data: 'studentname', title: "StudentName" },
{ data: 'fathername', title: "Father Name" },
{ data: 'rollno', title: "RollNo" },
{ data: 'mobile1', title: "Mobile" }
],
dom: 'Bfrtip',
iDisplayLength: 15,
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5',
'pageLength'
],
search: true
});
}
});
return false;
});

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

Resources