Laravel Ajax删除记录按钮



我不明白为什么它不起作用:

路线

Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController@deletebooking')->name('works.deletebooking');

资源控制器

public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}

<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>

请求Ajax

$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});

我有这个错误:

请求URL:http://pickbooking.local/dashboard/booking/deletebooking/1请求方式:POST状态代码:500内部服务器错误远程地址:192.168.10.10:80

问题在于用于ajax调用post的方法

// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});

数据将在请求的正文中发送,而在DELETE请求中,没有正文。因此laravel不会看到_method_token。要么在GET请求中发送它们,让_method完成它的工作(它将在url中,而不是在正文中(,要么在ajax调用中使用DELETE方法

// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});

因为我认为您有一个类似的错误

方法Illuminate\Database\Eloquent\Collection::delete不存在。

请尝试类似的方法

$booking = Booking::where('id', '=', $id)->first();
$booking->delete();

使得CCD_ 6可以具有方法CCD_

最新更新