【发布时间】:2018-03-05 09:34:03
【问题描述】:
我正在尝试通过 axios 向 laravel 发送删除请求,如下所示:
axios.delete('api/users/' + this.checkedNames)
.then((response) => {
console.log(response)
}, (error) => {
// error callback
})
现在,我从 axios 文档中了解到,对于删除请求,我们应该使用 configObject,因此可以将上面的内容重写为:
axios.delete('api/users/', {params: {ids:
this.checkedNames})
.then((response) => {
console.log(response)
}, (error) => {
// error callback
})
然后我在 api.php 中有Route::resource('users', 'UsersController');,所以删除的默认路由是:
DELETE| api/users/{user}| users.destroy
而控制器的方法是:
|App\Http\Controllers\UsersController@destroy
当我传递一个 id 比如说 api/users/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为什么当我传递一个数组时它可以工作而当我传递一个值时它却没有,为什么反之亦然带有方法delete的路由在传递一个数组时不会删除???
仅使用 api/users/destroy 与 api/users 之间有什么区别?
感谢您对此的任何帮助!
【问题讨论】:
-
感谢编辑,下一个问题会更加小心。