Laravel 表单不会 PATCH,只有 POST - 嵌套的 RESTfull 控制器,MethodNotAllowedHttpException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25857650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:06:28  来源:igfitidea点击:

Laravel form won't PATCH, only POST - nested RESTfull Controllers, MethodNotAllowedHttpException

laravellaravel-4laravel-routing

提问by maarten

I am trying to allow usersto edit their playlist. However, whenever I try to execute the PATCH request, I get the MethodNotAllowedHttpExceptionerror. (it is expecting a POST)

我正在尝试允许用户编辑他们的播放列表。但是,每当我尝试执行 PATCH 请求时,都会收到MethodNotAllowedHttpException错误。(它正在等待 POST)

I have set up RESTful Resource Controllers:

我已经设置了 RESTful 资源控制器:

Routes.php:

路线.php:

Route::resource('users', 'UsersController');
Route::resource('users.playlists', 'PlaylistsController');

This should give me access to: (as displayed through php artisan routes)

这应该让我可以访问:(如通过php artisan routes显示的)

URI                                        | Name                   | Action
PATCH users/{users}/playlists/{playlists}  | users.playlists.update | PlaylistsController@update

However, when I try to execute the following form, I get the MethodNotAllowedHttpExceptionerror:

但是,当我尝试执行以下表单时,出现MethodNotAllowedHttpException错误:

/users/testuser/playlists/1/edit

/users/testuser/playlists/1/edit

{{ Form::open(['route' => ['users.playlists.update', $playlist->id], 'method' => 'PATCH' ]) }}
{{ Form::text('title', $playlist->title) }}
{{ Form::close() }}

If I remove 'method'=> 'PATCH'I don't get an error, but it executes my public function store()and not my public function update()

如果我删除'method'=> 'PATCH'我不会收到错误,但它会执行我的public function store()而不是我的public function update()

回答by Alexander Lomia

Write {!! method_field('patch') !!}after form:

{!! method_field('patch') !!}在表格后写:

<form method="POST" action="patchlink">
     {!! method_field('patch') !!}
     . . .
</form>

Official documentation for helper function method_field()

帮助函数的官方文档 method_field()

回答by Sean Berce

In Laravel 5 and up:

在 Laravel 5 及更高版本中:

<form method="POST" action="patchlink">
    @method('patch')
    . . .
</form>

回答by Nenad

Since html forms support only GETand POSTyou need to add an extra hidden field to the form called _methodin order to simulate a PATCHrequest

由于 html 表单仅支持GET并且POST您需要向调用的表单添加一个额外的隐藏字段_method以模拟PATCH请求

<input type="hidden" name="_method" value="PATCH">

回答by mcha

As suggested by @Michael A in the comment above, send it as a POST

正如@Michael A 在上面的评论中所建议的,将其作为 POST 发送

<form method="POST" action="patchlink">
     <input type="hidden" name="_method" value="PATCH">

Worked for me.

对我来说有效。