2017-07-03 100 views
1

我正在構建一篇博客文章來學習Laravel 5.4,並且正在努力尋找任何有關如何更新Post的任何示例。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', '[email protected]'); 
 

 
Route::patch('/posts/{post}', '[email protected]');

而且我的控制方法是

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函數的點,或者可能只是我批量分配新值的方式。任何幫助將不勝感激。

+0

您應該在表單中添加「。 – Maraboc

回答

4

你應該使用

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

謝謝,這工作完美!我的控制器更新功能也有問題嗎?在這些變化之後剛剛得到'方法更新不存在'錯誤 – helenkitt

+0

@helenkitt這可能是因爲在控制器中使用'$ request-> all();'所以它試圖更新表上的CSRF標記字段不存在。 –

2

有幾件事情你有誤d出來。

首先,@Maraboc在評論中指出的,你需要添加方法欺騙作爲標準的HTML表單只允許GETPOST方法:

<input type="hidden" name="_method" value="PATCH"> 

{{ method_field('PATCH') }} 

https://laravel.com/docs/5.4/routing#form-method-spoofing

然後,您還需要在表單操作中省略「編輯」uri:

<form method="POST" action="/posts/{{ $post->id }}"> 

​​

https://laravel.com/docs/5.4/controllers#resource-controllers

(向下滾動一點點地處理好通過資源控制器部分操作)

你也可以發現它有助於觀看https://laracasts.com/series/laravel-5-from-scratch/episodes/10

希望這個他LPS!