Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel FormRequest response status code on failed validation

Tags:

php

laravel

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

  • Why does $this->getValidatorInstance()->failed return empty array?
  • How can I fix that? Is there some other way to return status code depending on failed validation rule?
like image 304
Ivan Avatar asked Oct 21 '25 17:10

Ivan


1 Answers

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!

like image 60
Rwd Avatar answered Oct 24 '25 09:10

Rwd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!