Reputation:
I am using Laravel's form request validation, which I find very useful, and is making my controllers a lot tidier.
My more complex validation pieces, which, if the Validator
fails, should return back to the previous page, with the user's old input.
I also, sometimes, have to specify a named error bag, which again, doesn't seem to come built in as an option to the request forms.
Unfortunately, this additional error functions doesn't appear to come by default with the form requests validator.
At the moment I have:
$validator = Validator::make($request->all(), [
'id' => 'required|numeric',
'name' => 'required|alpha_spaces',
'email' => 'required|email',
]);
if ($validator->fails()) {
return back()
->withErrors($validator, 'aNamedErrorBag')
->withInput();
}
Is there a way to extract the rules into a request validator file, and return with input to the named error bag aNamedErrorBag
, should the validator fail?
Many thanks
Upvotes: 1
Views: 1702
Reputation: 50798
The FormRequest
class juggles the name of the error bag as a property:
/**
* The key to be used for the view error bag.
*
* @var string
*/
protected $errorBag = 'default';
You can change this value to the errorBag that you want the errors to be sent to. Simply add it to your custom request class as a property.
Edit
This is what the FormRequest returns on the validation error:
/**
* 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);
}
Upvotes: 0