Laravel 5.4 - 更新资源

标签 laravel crud laravel-5.4

我正在构建一篇博客文章来学习 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/

相关文章:

php - Laravel只搜索7天的记录

c# - 脚手架项目的包恢复失败问题

php - 是否有 PHP 工具可以从数据库模式生成 CRUD 屏幕?

javascript - 使用远程jquery验证来检查电子邮件是否已经存在?

php - 使用 Maatwebsite 的 laravel Excel impoirtation 找不到一些列

php - Laravel 多路由别名

php - 无法通过 postman 的放置请求提交表单数据

php - MySQL SELECT 查询获取记录如果 is_default = 1 否则 is_default = 0?

yii - 关于 Yii 中的 CRUD 生成器

redis - laravel 回显服务器,redis