2016-03-08 31 views
1

我想更新一篇文章。創建和刪除帖子可以很好地工作,但每當我嘗試使用PATCH表單進行更新時,它都會失敗,並提供MethodNotAllowedHttpExceptionLaravel 5.2 MethodNotAllowedHttpException帶有修補程序的路由:: resource

我routes.php文件:

... 
Route::resource('posts', 'PostsController'); 
... 

這給了我可能的路線如下表(CSS中粘貼保持可讀性):

| GET|HEAD | posts     | posts.index   | App\Http\Controllers\[email protected] 
| POST  | posts     | posts.store   | App\Http\Controllers\[email protected]  
| GET|HEAD | posts/create    | posts.create   | App\Http\Controllers\[email protected]  
| GET|HEAD | posts/{posts}   | posts.show   | App\Http\Controllers\[email protected]   
| DELETE | posts/{posts}   | posts.destroy  | App\Http\Controllers\[email protected]   
| PUT|PATCH | posts/{posts}   | posts.update   | App\Http\Controllers\[email protected]  
| GET|HEAD | posts/{posts}/edit  | posts.edit   | App\Http\Controllers\[email protected] 

我edit.blade.php(URL =本地主機:8000 /職位/ 1 /編輯):

{!! Form::model($post, ['method' => 'PATCH', 'action' => ['[email protected]', $post]]) !!} 
     @include('posts/_form', array('submitText' => 'Update')) 
    {!! Form::close() !!} 

我的PostsController:

public function update(Request $request, Post $post) { 
     $post->update($request->all()); 
     return Redirect::route('posts.index')->with('message_succes', 'Post updated'); 
} 

無論我嘗試,它失敗與

MethodNotAllowedHttpException RouteCollection-> methodNotAllowed(陣列( 'GET', 'HEAD', 'POST'))在 RouteCollection.php線206

查看錶格的HTML源代碼,並正確插入標記。 將PATCH更改爲在表單中發佈時,它將使用商店功能並創建一個新帖子。我需要做些什麼來更新帖子?

+2

你應該只傳遞一個表單動作的id。你用'$ post'。由於您沒有共享'edit()'方法,我們不知道'$ post'變量中返回的是什麼。如果$ post是一個集合,使用'['PostController @ update',$ post-> id]'。如果不行,請分享'edit()'方法的代碼。 – smartrahat

+0

@smartrahat是的,你是對的。已經發現我確實發佈了完整的對象。現在正在工作。 – Trekdrop

回答

0

嘗試改變PATCH方法把在這樣的形式:

{!! Form::model($post, ['method' => 'PUT', 'action' => ['[email protected]', $post]]) !!} 
    @include('posts/_form', array('submitText' => 'Update')) 
{!! Form::close() !!} 
+0

感謝您的回覆。它給了我同樣的錯誤。還有一件事要說的是,這些字段沒有填充條目。 – Trekdrop

1

原來,我張貼了完整的對象,而不是隻有ID。 我不得不改變:在形式和PostController的更新

$post$post->id

public function update(Request $request, $post_id) { 
     $post = Post::findOrFail($post_id) 
     $post->update($request->all()); 
     return Redirect::route('posts.index')->with('message_succes', 'Post updated'); 
} 
-1

尼斯,你是正確的!但是你反過來說,$ post-> id爲$ post,那麼控制器將使用整個對象來代替單個對象。現在在這裏工作。謝謝!

0

對於那些,誰只是忘了指定編輯表單動作/路線,即:

{!! Form::model($post, ['method' => 'PATCH']) !!} 
    ... 
    Form controls 
    ... 
{!! Form::close() !!} 

如果不顯式指定editupdate形式的行動,Form::model()將使用當前的路線,例如<site>/posts/<id>/edit。所以,不要忘了真正update動作的位置,或者通過路線:

{!! Form::model($post, ['method' => 'PATCH', 'route' => ['posts.update', $post]]) !!} 
    ... 
    Form controls 
    ... 
{!! Form::close() !!} 

...這是我個人比較喜歡,「職高它更普遍,或通過的行動:

{!! Form::model($post, ['method' => 'PATCH', 'action' => ['[email protected]', $post->id]]) !!} 
    ... 
    Form controls 
    ... 
{!! Form::close() !!} 

..這略顯過於冗長和具體。