我正在使用Laravel的表单请求验证,我发现它非常有用,并且使我的控制器更加整洁。
我更复杂的验证作品,如果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
,验证器是否失败?
非常感谢
FormRequest
类将错误袋的名称jugg作为属性:
/**
* The key to be used for the view error bag.
*
* @var string
*/
protected $errorBag = 'default';
您可以将此值更改为希望将错误发送到的错误袋。只需将其添加到您的自定义请求类中。
编辑
这是formrequest在验证错误上返回的内容:
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return SymfonyComponentHttpFoundationResponse
*/
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);
}