2017-06-06 64 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