2017-06-12 68 views
1

最近我開始了一個Laravel 5.4項目,我發現了一些我不太明白的東西,我發佈了這個問題,希望能夠解決這個問題,並確定它是否是預期的行爲或者錯誤。Laravel 5.4重定向從請求對象的方法

的事情是,我提交它看起來像這樣的更新形式:

<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(); 
} 

我的問題是當驗證失敗並執行重定向,因爲我得到一個代碼錯誤MethodNotAllowedHttpException

事實上,網址是正確的,但方法是錯誤的,因爲在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())權之前重定向呼叫:

  • 取消設置從請求中_method:unset($request['_method'])
  • 名稱路線

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

    我已經沒有運氣嘗試了一些東西並以此名稱重定向:

    // The routes file (routes/web.php) 
    Route::get('posts/{id}/edit', '[email protected]')->name('edit-post'); 
    
    // The redirect (controller) 
    return redirect()->route('edit-post', ['id' => 1]) 
        ->withErrors($validator) 
        ->withInput(); 
    
  • 指定重定向

    // The redirect (controller) 
    return redirect('admin/posts/'.$post->id.'/edit') 
        ->withErrors($validator) 
        ->withInput(); 
    

所以,我怎麼能執行一個正常的GET方法重定向的URL?這是預期的行爲嗎?預先感謝您,任何建議或提示,非常感謝。

回答

0

您需要在您的routes.php文件中有單獨的放置路線。

Route::get('posts/{id}/edit', '[email protected]')->name('edit-post'); 
Route::put('posts/{id}/edit', '[email protected]')->name('edit-post'); 

get函數表示該路由將使用GET方法處理路由。您需要添加put以使用PUT方法處理請求。所有可用的路線方法可在the documentation


您還可以使用匹配功能在一行中匹配多個方法。像這樣:

Route::match(['get', 'put'], 'posts/{id}/edit', '[email protected]'); 
+0

因此,使用請求對象中存在的方法執行重定向是一種預期的行爲? – Asur