I've created a custom FormRequest to validate requests relating to a particular product with attributes. One of the rules is, of course, that the request product field exists in the products database.
However, I have a more complicated rule that must be checked after. I'm checking this rule using the withValidator method, and then doing:
$validator->after(function ($validator) {
// check the extra rule
...
});
(It doesn't particularly matter, but this rule is to check that, given the user selected attributes like color and size, this corresponds to a unique sku belonging to the product)
So how do I cause the validation to fail?
Another requirement is that when this validation fails, it should return a 500 instead of a 422. Additionally, it should return a custom JSON response if this sku is out of stock. How do I do this within FormRequest?
To add an error in an after hook you can do it like so:
$validator->after(function ($validator) {
if (!$someCondition) {
$validator->errors()->add('key', 'Some error message explaining error.');
}
});
If you are validating the product field, then the 'key' should be 'product'.
For the second requirement you can override the failedValidation function.
protected function failedValidation(Validator $validator)
{
throw (new ValidationException($validator))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl())
->status(500);
}
Now if you need to send a custom response, you could check for the 500 status in your App\Exceptions\Handler.php
public function render($request, Throwable $exception)
{
if (is_a($exception, ValidationException::class) && $exception->getCode() === 500) {
// Handle your custom JSON reponse
}
return parent::render($request, $exception);
}
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