我尝试使用Laravel(5.3)destroy方法在按下按钮时删除对象,但我得到的是MethodNotAllowedHttpException。
我的路线是
Route::delete('/admin/add/{id}', 'ItemController@destroy');
destroy方法是
public function destroy($id)
{
$items = Item::where('id', $id)->get();
foreach ($items as $item)
$item->delete();
return redirect('/admin/add');
}
我的表单是
<form action="{{ url('admin/add/'.$specific->id)}}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<div class="modal-footer no-border">
<button type="submit" class="btn btn-primary">Delete</button>
</div>
</form>
我检查了现有的路线(php artisan route:list),删除的路线显示:
DELETE | admin/add/{id} | | App\Http\Controllers\ItemController@destroy
我得到的错误是
in RouteCollection.php line 218
at RouteCollection->methodNotAllowed(array('GET', 'HEAD', 'POST')) in RouteCollection.php line 205
at RouteCollection->getRouteForMethods(object(Request), array('GET', 'HEAD', 'POST')) in RouteCollection.php line 158
at RouteCollection->match(object(Request)) in Router.php line 766
at Router->findRoute(object(Request)) in Router.php line 621
at Router->dispatchToRoute(object(Request)) in Router.php line 607
at Router->dispatch(object(Request)) in Kernel.php line 268
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Kernel.php line 150
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 117
at Kernel->handle(object(Request)) in index.php line 53
at require('/Users/username/Sites/blades/public/index.php') in server.php line 133
根据Laravel路由说明,我使用表单并使用POST方法欺骗DELETE操作,但我仍然遇到异常。任何帮助将不胜感激。
注意:我按照https://laravel.com/docs/5.2/quickstart-intermediate处的完整示例进行操作,在那里完全正常。我试图在另一个项目中重建这个问题是导致这个问题的原因。
答案 0 :(得分:0)
在浏览器中打开开发者控制台并打开网页后,请检查$specific->id
不为空,如dd($specific->id)
,并检查网址是否正确。
答案 1 :(得分:0)
我发现了问题。此表单所在的页面上面有一个不同的POST表单,我使用</div>
而不是</form>
标记关闭了表单。因此,它试图同时提交两个表单,并且POST调用是冲突的。