【问题标题】:Laravel FormRequest response status code on failed validationLaravel FormRequest 验证失败的响应状态码
【发布时间】:2017-01-05 04:28:42
【问题描述】:

我正在为我的 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()->failed 返回空数组?
  • 我该如何解决这个问题?是否有其他方法可以根据失败的验证规则返回状态码?

【问题讨论】:

  • 你用的是什么版本的 laravel?
  • 我使用 Laravel 5.3

标签: php laravel


【解决方案1】:

调用$this->getValidatorInstance()->failed() 时得到一个空数组的原因是它实际上是在解析Validator 的一个新实例。

您可以在新的Validator 实例上调用passes(),然后您可以调用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);
}

希望这会有所帮助!

【讨论】:

  • 是的,我可以这样做,但在这种情况下,我会验证数据两次,所以它对我没有帮助
  • 我做不到,bcs 我得到“声明 ...GetUser::response(array $errors, $validator) 应该与 ...FormRequest::response(array $错误)”至少,我要创建自己的课程。你能告诉我,我应该怎么做?我的意思是,我应该在哪里创建它?我以为我可以创建 Facade,但我不能这样做,或者文档对此没有说什么:)
  • @Ivan 哦,是的,当然可以。在这种情况下,您可以将其添加到 FormRequest 中的属性中,然后在之后引用它。我已经更新了我的答案。
  • 感谢您的帮助。没关系,我要创建新课程,因为我必须创建 20 个这样的课程 :)
  • @Ivan 很高兴我能帮上忙!只需使用上述逻辑创建一个类并让你的二十个类扩展它......
猜你喜欢
  • 2017-07-28
  • 1970-01-01
  • 2018-03-06
  • 2018-06-01
  • 2022-07-23
  • 2021-06-02
  • 1970-01-01
  • 2019-05-05
  • 2020-06-25
相关资源
最近更新 更多