Laravel 5.4 - Updating a resource

Viewed 27346

I'm building a blog post to learn Laravel 5.4 and am struggling to find any examples of how to update a Post anywhere.

My form is as follows

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

My Routes are as follows

Route::get('/posts/{post}/edit', 'PostsController@edit');

Route::patch('/posts/{post}', 'PostsController@update');

And my controller methods are

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');

}

I get a MethodNotAllowedHTTPException error but am not sure which part / parts of this I am getting wrong.

I'm assuming it must be the point at which I'm using the PATCH function, or potentially just the way I'm mass-assigning the new values. Any help would be greatly appreciated.

3 Answers

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON.

Related