Laravel 5.4-更新资源

问题描述 投票:4回答:3

[我正在构建一个博客文章以学习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函数的点,或者可能仅仅是我批量分配新值的方式。任何帮助将不胜感激。

laravel crud laravel-5.4
3个回答
11
投票
您应该使用

{{ 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>


3
投票
您错过了几件事。

首先,正如@Maraboc在注释中指出的那样,您需要添加方法欺骗,因为标准HTML格式仅允许GETPOST方法:

<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有帮助

希望这会有所帮助!


0
投票
[构建API时,您可能需要一个转换层,位于Eloquent模型与实际返回给应用程序用户的JSON响应之间。 Laravel的资源类使您可以表达而轻松地将模型和模型集合转换为JSON。
© www.soinside.com 2019 - 2024. All rights reserved.