I'm creating validation (via FormRequest ) for my API and I need to change status code depending on failed validation rule (e.g. If id is string instead of int, get 400. If id doesn't exists, get 404).
I wanted to write something like that:
/**
* Get the proper failed validation response for the request.
*
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
$failedRules = $this->getValidatorInstance()->failed();
$statusCode = 400;
if (isset($failedRules['id']['Exists'])) $statusCode = 404;
return response($errors, $statusCode);
}
However, $this->getValidatorInstance()->failed() returns empty array
The reason you're getting an empty array when your call $this->getValidatorInstance()->failed() is because it's actually resolving a new instance of Validator.
What you can do is call passes() on the new Validator instance which will then allow you to call failed() to get the rules:
$validator = $this->getValidatorInstance();
$validator->passes();
$failedRules = $validator->failed();
Alternatively, if you don't want to have the validator run twice you could override the failedValidation method to store the Validation instance in class:
protected $currentValidator;
protected function failedValidation(Validator $validator)
{
$this->currentValidator = $validator;
throw new ValidationException($validator, $this->response(
$this->formatErrors($validator)
));
}
public function response(array $errors)
{
$failedRules = $this->currentValidator->failed();
$statusCode = 400;
if (isset($failedRules['id']['Exists'])) $statusCode = 404;
return response($errors, $statusCode);
}
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With