首页 文章

Laravel 5.4从请求对象重定向获取方法

提问于
浏览
1

最近我开始了一个Laravel 5.4项目,我找到了一些我不太了解的东西,我发布了这个问题,希望能解决这个问题并找出它是预期的行为还是一个bug .

问题是,我正在提交一个看起来像这样的更新表:

<form id="post-form" action="{{url('admin/posts/'.$post->id)}}" method="POST">
  {{ csrf_field() }}
  {{ method_field('PUT') }}
  <!-- Some fields -->
</form>

我尝试在控制器方法上验证该请求:

$validator = Validator::make($request->all(), [
        // Fields to validate
    ]);
if ($validator->fails()) {
   return back()
   ->withErrors($validator)
   ->withInput();
}

验证失败并执行重定向时出现问题,因为我收到代码 405 错误 MethodNotAllowedHttpException .

实际上,url是正确的,但方法是错误的,如HTTP标头中所示:

Request URL:https://myproject.dev/admin/posts/1/edit
Request Method:PUT
Status Code:405 
Remote Address:127.0.0.1:443
Referrer Policy:no-referrer-when-downgrade

应该是GET而不是PUT . 我最好的猜测是使用 $request 对象的_method属性来重定向,而不是使用GET方法 .

在重定向呼叫之前的 dump($request->all())

array:19 [
  "_token" => "XOtwEeXwgnuc8fNqCwxkdO992bU6FObDwTuCg1cJ"
  "_method" => "PUT"
  //fields
]

有些事情我已经尝试过没有运气:

  • 从请求中取消设置_method: unset($request['_method'])

  • 根据该名称命名路由和重定向:

// The routes file (routes/web.php)
Route::get('posts/{id}/edit', 'PostsController@edit')->name('edit-post');

// The redirect (controller)
return redirect()->route('edit-post', ['id' => 1])
    ->withErrors($validator)
    ->withInput();
  • 指定重定向中的URL
// The redirect (controller)
return redirect('admin/posts/'.$post->id.'/edit')
    ->withErrors($validator)
    ->withInput();

那么我怎么能用普通的GET方法执行重定向呢?这是预期的行为吗?提前感谢您,任何建议或提示都非常感谢 .

1 回答

  • 0

    您需要在 routes.php 文件中使用单独的放置路径 .

    Route::get('posts/{id}/edit', 'PostsController@edit')->name('edit-post');
    Route::put('posts/{id}/edit', 'PostsController@edit')->name('edit-post');
    

    get 函数表示此路由将使用GET方法处理路由 . 您需要使用PUT方法添加 put 来处理请求 . 所有可用的路线方法均可在the documentation中找到 .


    您还可以使用匹配函数在一行中匹配多个方法 . 像这样:

    Route::match(['get', 'put'], 'posts/{id}/edit', 'PostsController@edit');
    

相关问题