如何使用自定义规则在Laravel表单请求中抛出404

问题描述

通常,Laravel的表单请求会在验证失败时返回通用的400代码,如下所示:

{
  "message": "The given data is invalid","errors": {
    "person_id": [
      "A person with ID c6b853ec-b53e-4c35-b633-3b1c2f27869c does not exist"
    ]
  }
}

如果请求未通过我的自定义规则,我想返回404。

我的自定义规则检查数据库中是否存在记录:

class ValidatePersonExists implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
    public function passes($attribute,$value)
    {
        return Person::where('id',$value)->exists();
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return "A person with ID :input does not exist";
    }
}

如果我在ModelNotFoundException检查失败时抛出了exists(),我在哪里可以捕捉到它以友好的404响应进行响应?

这是我使用规则的表单请求:

public function rules()
{
    return [
        'person_id' => ['bail','required','uuid',new ValidatePersonExists],];
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)