删除方法在爱可信,Laravel和VueJS
我试图通过爱可信发送删除请求到laravel如下:删除方法在爱可信,Laravel和VueJS
axios.delete('api/users/' + this.checkedNames)
.then((response) => {
console.log(response)
}, (error) => {
// error callback
})
现在从爱可信文件我读了删除请求,我们应该使用一个configObject所以上述可改写为这样:
axios.delete('api/users/', {params: {ids:
this.checkedNames})
.then((response) => {
console.log(response)
}, (error) => {
// error callback
})
我有那么Route::resource('users', 'UsersController');
在api.php所以删除默认路由是:
DELETE| api/users/{user}| users.destroy
和控制器的方法是:
|App\Http\Controllers\[email protected]
我能当我通过一个ID假设API /用户/ 12,它被正确地删除,但删除预期用户,当我尝试通过上面的数组变得复杂。
如果我尝试按照axios文档axios.delete('api/users/', {params: {id: this.checkedNames}})
它看起来我发送这个http://lorillacrud.dev/api/users?id[]=21&id[]=20
但我得到405方法不允许。
如果我尝试axios.delete('api/users/' + this.checkedNames)
我得到http://lorillacrud.dev/api/users/20,21
所以在我的销毁方法,我可以抓住id和删除,但我想知道这是否是正确的方法吗?
更新
我好像我做了工作,但我不理解所以还是赞赏做什么我做实际工作的感觉任何帮助!
因此,如果变化:
axios.delete('api/users/destroy', {params: {'id': this.checkedNames})
,并在我的破坏方法:
if ($request->id) {
foreach ($request->id as $id) {
User::destroy($id);
}
}
User::destroy($id);
}
所以......
// not deletes the user
axios.delete('api/users/destroy', {params: {id: id}})
// ok deletes the users when using request->id in a for loop in the destroy laravel method.
axios.delete('api/users/destroy', {params: {ids: this.checkedNames}})
// ok deletes one user
axios.delete('api/users/' + id)
对不起你们,但我有很多的困惑为什么和什么!
路由名称为user.destroy
为什么当我传递一个数组时,它不工作,当我传递一个单值时,为什么viceversa方法删除的路由在传递数组时不会删除?
使用api/users/destroy
与api/users
仅有什么区别?
感谢您的任何帮助!
这是因为方法签名。使用Resource
时,默认delete
路由需要单个参数。这样做的时候:
axios.delete('api/users', {params: {'id': this.checkedNames})
你缺少一个需要参数。路由定义是
Route::delete('api/users/{id}', '[email protected]');
// You are missing `id` here. So it won't work.
通常,如果您要偏离默认行为,建议您创建自己的函数。因此,您可以保留默认的destroy($id)
函数来删除单个条目并编写一个删除许多条目的新函数。通过添加路由开始为它
Route::delete('api/users', '[email protected]');
然后定义函数来处理它
public function deleteMany(Request $request)
{
try
{
User::whereIn('id', $request->id)->delete(); // $request->id MUST be an array
return response()->json('users deleted');
}
catch (Exception $e) {
return response()->json($e->getMessage(), 500);
}
}
总之,你的问题就来了,从路由定义。您的路线从Axios与Laravel的路线定义不符,因此是405.
好吧,我明白了,非常感谢我正在专注于params,而错误是在laravel一边!感谢您指出了这一点。 –
感谢您的编辑,下一个问题会更加谨慎。 –