2017-06-06 56 views
0

我正在使用Laravel的form request validation,我發現它非常有用,並且使我的控制器更加整潔。表單請求驗證返回錯誤與舊輸入

我的更復雜的驗證件,如果Validator失敗,應使用用戶的舊輸入返回到上一頁。

我也有時不得不指定一個指定的錯誤包,它似乎並不是作爲請求表單的一個選項內置的。

不幸的是,這個額外的錯誤函數似乎並沒有在表單請求驗證器中出現。

目前我有:

$validator = Validator::make($request->all(), [ 
    'id' => 'required|numeric', 
    'name' => 'required|alpha_spaces', 
    'email' => 'required|email', 
]); 

if ($validator->fails()) { 
    return back() 
     ->withErrors($validator, 'aNamedErrorBag') 
     ->withInput(); 
} 

有沒有一種方法來提取規則到請求驗證的文件,並與輸入返回到指定的錯誤袋aNamedErrorBag,如果驗證失敗?

非常感謝

回答

0

FormRequest類種子隊的錯誤袋爲屬性的名稱:

/** 
* The key to be used for the view error bag. 
* 
* @var string 
*/ 
protected $errorBag = 'default'; 

您可以將此值更改爲你想要的錯誤發送給errorBag。只需將其作爲屬性添加到您的自定義請求類中即可。

編輯

這就是FormRequest的驗證錯誤返回:

/** 
* Get the proper failed validation response for the request. 
* 
* @param array $errors 
* @return \Symfony\Component\HttpFoundation\Response 
*/ 
public function response(array $errors) 
{ 
    if ($this->expectsJson()) { 
     return new JsonResponse($errors, 422); 
    } 

    return $this->redirector->to($this->getRedirectUrl()) 
            ->withInput($this->except($this->dontFlash)) 
            ->withErrors($errors, $this->errorBag); 
} 
+0

好極了!謝謝@Ohgodwhy。它會默認返回用戶的舊輸入嗎? – Ben

+1

@Ben Yup。我添加了將錯誤的FormRequest驗證數據返回給答案的函數。 – Ohgodwhy

+0

更好。再次感謝Ohgodway :) – Ben