Laravel Datatable delete record with sweetalert dont working - laravel

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

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

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

double insert in database while submiting form using Ajax in laravel

I'm trying to submit my form with ajax.
So I'm using the following ajax code:
<script>
if ($("#castingform").length > 0) {
$("#castingform").validate({
rules: {
casting_name: {
required: true,
maxlength: 50
},
casting_photo: {
required: true
},
},
messages: {
casting_name: {
required: "Please enter name",
maxlength: "Name should be 50 characters long."
},
casting_photo: {
required: "Please enter photo"
},
},
submitHandler: function(form) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#castingform').on('submit', function(event) {
event.preventDefault();
$.ajax({
url:"{{ url('castings') }}",
method:"POST",
data:new FormData(this),
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success:function(res) {
$("#createBtn").removeClass("disabled");
$("#createBtn").text("Sign in");
if (res.status == "success") {
$(".result").html("<div class='alert alert-success rounded'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
/* location.reload();*/
} else if(res.status == "failed") {
$(".result").html("<div class='alert alert-danger alert-dismissible'><button type='button' class='close' data-dismiss='alert'>×</button>" + res.message+ "</div>");
}
}
});
});
}
})
}
</script>
But when I click for the first time on the button submit, the success message doesn't show, and for the second time I get the success message but I find a double insert in the database.
My Controller
EDIT
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'casting_name' => 'required',
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->passes()) {
$input['casting_photo'] = time().'.'.$request->casting_photo->extension();
$request->casting_photo->move(public_path('castingimages'), $input['casting_photo']);
$data = [
'casting_name' => $request->casting_name,
'casting_photo'=> $input['casting_photo']
];
Casting::create($data);
return response()->json([
"status" => "success",
"message" => "Success! post created."
]);
}
return response()->json([
"status" => "failed",
"message" => "Alert! post not created"
]);
}
I think the problem is in this line submitHandler: function(form) and this line $('#castingform').on('submit', function(event) {, but I don't know how to solve it.

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

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

Resources