我正在构建一篇博客文章来学习 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');
我的 Controller 方法是
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>
关于Laravel 5.4 - 更新资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44883661/