[我正在构建一个博客文章以学习Laravel 5.4,并且正在努力寻找有关如何在任何地方更新帖子的示例。
我的表格如下
<form method="POST" action="/posts/{{ $post->id }}/edit">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input name="title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="{{ $post->title }}" required>
</div>
<div class="form-group">
<label for="description">Description</label>
<input name="description" type="text" class="form-control" id="exampleInputPassword1" value="{{ $post->title }}" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
我的路线如下
Route::get('/posts/{post}/edit', 'PostsController@edit');
Route::patch('/posts/{post}', 'PostsController@update');
我的控制器方法是
public function edit( Post $post )
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, Post $post )
{
Post::where('id', $post)->update($request->all());
return redirect('home');
}
我收到MethodNotAllowedHTTPException
错误,但不确定我弄错了哪一部分。
我假设它一定是我使用PATCH函数的点,或者可能仅仅是我批量分配新值的方式。任何帮助将不胜感激。
{{ method_field('PATCH') }}
作为您的表单字段并将动作更改为
/posts/{{ $post->id }}
像这样:
<form method="POST" action="/posts/{{ $post->id }}"> {{ csrf_field() }} {{ method_field('PATCH') }} <div class="form-group"> <label for="title">Title</label> <input name="title" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="{{ $post->title }}" required> </div> <div class="form-group"> <label for="description">Description</label> <input name="description" type="text" class="form-control" id="exampleInputPassword1" value="{{ $post->title }}" required> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Update</button> </div> </form>
首先,正如@Maraboc在注释中指出的那样,您需要添加方法欺骗,因为标准HTML格式仅允许GET
和POST
方法:
<input type="hidden" name="_method" value="PATCH">
或
{{ method_field('PATCH') }}
https://laravel.com/docs/5.4/routing#form-method-spoofing然后,您还需要在表单操作中省略“ edit” uri:
<form method="POST" action="/posts/{{ $post->id }}">
或
<form method="POST" action="{{ url('posts/' . $post->id) }}">
https://laravel.com/docs/5.4/controllers#resource-controllers(向下滚动到
资源控制器处理的操作]部分)[您可能还会发现观看https://laracasts.com/series/laravel-5-from-scratch/episodes/10有帮助
希望这会有所帮助!