Laravel编辑帖不起作用

时间:2017-03-07 13:21:09

标签: laravel

有路线

Route::get('posts', 'PostsController@index');
Route::get('posts/create', 'PostsController@create');
Route::get('posts/{id}', 'PostsController@show')->name('posts.show');
Route::get('get-random-post', 'PostsController@getRandomPost');
Route::post('posts', 'PostsController@store');
Route::post('publish', 'PostsController@publish');
Route::post('unpublish', 'PostsController@unpublish');
Route::post('delete', 'PostsController@delete');
Route::post('restore', 'PostsController@restore');
Route::post('change-rating', 'PostsController@changeRating');

Route::get('dashboard/posts/{id}/edit', 'PostsController@edit');
Route::put('dashboard/posts/{id}', 'PostsController@update');

Route::get('dashboard', 'DashboardController@index');
Route::get('dashboard/posts/{id}', 'DashboardController@show')->name('dashboard.show');
Route::get('dashboard/published', 'DashboardController@published');
Route::get('dashboard/deleted', 'DashboardController@deleted');
PostsController中的

方法

public function edit($id) 
{
    $post = Post::findOrFail($id);  
    return view('dashboard.edit', compact('post'));
}

public function update($id, PostRequest $request) 
{
    $post = Post::findOrFail($id);
    $post->update($request->all());
    return redirect()->route('dashboard.show', ["id" => $post->id]);
}

但是当我更改帖子并点击提交按钮时,我收到错误

  

RouteCollection.php第233行中的MethodNotAllowedHttpException:

怎么了?如何解决?

UPD

从视图中打开表单

{!! Form::model($post, ['method'=> 'PATCH', 'action' => ['PostsController@update', $post->id], 'id' => 'edit-post']) !!}

因此我得到了

<form method="POST" action="http://mytestsite/dashboard/posts?6" accept-charset="UTF-8" id="edit-post"><input name="_method" type="hidden" value="PATCH"><input name="_token" type="hidden" value="aiDh4YNQfLwB20KknKb0R9LpDFNmArhka0X3kIrb">

但为什么这个动作http://mytestsite/dashboard/posts?6 ???

3 个答案:

答案 0 :(得分:2)

尝试在您的路线中使用patch代替put进行更新。

  

只需一个小小的提示,您可以通过在参数中声明模型来节省能源和一点时间:

public function update(Post $id, PostRequest $request) 

并摆脱这个

 $post = Post::findOrFail($id);  
  

修改

您可以在表单中使用网址而不是操作:

'url'=> '/mytestsite/dashboard/posts/{{$post->id}}'

答案 1 :(得分:0)

根据错误消息,最可能的原因是动作和路线不匹配。也许路由需要POST方法,但操作是GET。检查一下。

答案 2 :(得分:0)

尝试在隐藏输入中发送帖子ID,不要像使用'action'=&gt;那样使用smt ['PostsController @ update',$ post-&gt; id] 它有助于结果动作网址。