Laravel FormRequest响应状态代码验证失败

时间:2017-01-04 17:39:07

标签: php laravel

我正在为我的API创建验证(通过FormRequest),我需要根据失败的验证规则更改状态代码(例如,如果id是字符串而不是int,则获取400.如果id不存在则得到404)。

我想写这样的东西:

/**
 * 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);
}

然而,$ this-> getValidatorInstance() - > failed()返回空数组

  • 为什么$ this-> getValidatorInstance() - >失败返回空数组?
  • 我该如何解决?是否有其他方法可以根据失败的验证规则返回状态代码?

1 个答案:

答案 0 :(得分:1)

在您致电$this->getValidatorInstance()->failed()时,您获得空数组的原因是因为它实际上正在解析Validator的新实例。

您可以在新的passes()实例上致电Validator,然后您可以致电failed()来获取规则:

$validator = $this->getValidatorInstance();
$validator->passes();
$failedRules = $validator->failed();

或者,如果您不希望验证程序运行两次,则可以覆盖failedValidation方法以在类中存储Validation实例:

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);
}

希望这有帮助!