Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 验证失败时的Laravel FormRequest响应状态代码_Php_Laravel - Fatal编程技术网

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

Php 验证失败时的Laravel FormRequest响应状态代码,php,laravel,Php,Laravel,我正在为我的API创建验证(通过FormRequest),我需要根据失败的验证规则更改状态代码(例如,如果id是string而不是int,则获取400。如果id不存在,则获取404) 我想写这样的东西: /** * Get the proper failed validation response for the request. * * @param array $errors * @return \Symfony\Component\HttpFoundation\Response

我正在为我的API创建验证(通过FormRequest),我需要根据失败的验证规则更改状态代码(例如,如果id是string而不是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返回空数组
  • 我怎样才能解决这个问题?是否有其他方法根据失败的验证规则返回状态代码

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

您可以在新的
验证程序
实例上调用
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);
}

希望这有帮助

您使用的是什么版本的laravel?我使用laravel 5.3是的,我可以这样做,但在这种情况下,我会验证数据两次,这样对meI没有帮助。我不能这样做,bcs我得到“声明…GetUser::response(array$errors,$validator)应该与…FormRequest::response(array$errors)”兼容,至少,我要创建我自己的类。你能告诉我,我该怎么做吗?我的意思是,我应该在哪里创建它?我以为我可以创建Facade,但我做不到,或者docs没有说任何关于它的事情:)@Ivan哦,是的,当然有。在这种情况下,您可以将它添加到FormRequest中的属性中,然后在之后引用它。我已经更新了我的答案。谢谢你的帮助。没关系,我要创建一个新类,bcs我必须创建二十个这样的类:)@Ivan很高兴我能帮上忙!只需使用上述逻辑创建一个类,并让您的二十个类对其进行扩展。。。