You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel如何验证category属性归属指定用户 解决不存在ID报错问题

问题描述

大家好,我在尝试验证分类(category)是否归属指定用户时遇到了问题:当传入不存在的分类ID时会抛出错误,我尝试的写法如下:

'category' => ['nullable','exists:categories,id', function ($attribute, $value, $fail) {
    $category = Category::where('id', $value)->first();
    if($category->vcard!= $this->vcard->phone_number)
    {
       $fail('The selected category is invalid.');
    }
}]

该规则在输入合法分类ID时运行正常,但输入不存在的ID(比如100000)时Postman会抛出错误,我原本认为exists:categories,id规则可以过滤不存在的ID,请问为什么会出现该问题?

正常运行的请求示例:

{
 "payment_reference": "a1@mail.com",
 "payment_type": "PAYPAL",
 "type": "D",
 "value": 10,
 "description": "Teste",
 "category": 500
}

触发错误的请求示例:

{
 "payment_reference": "a1@mail.com",
 "payment_type": "PAYPAL",
 "type": "D",
 "value": 10,
 "description": "Teste",
 "category": 1000000
}

问题原因

Laravel的验证规则默认会执行所有定义的验证项,就算前面的exists:categories,id已经判定ID不存在,后面的自定义闭包验证依然会运行。当传入的分类ID不存在时,Category::where('id', $value)->first()会返回null,此时调用$category->vcard就会抛出非对象访问属性的错误。

修复方案

方案1:添加bail规则终止后续验证

在exists规则前加上bail规则,该规则作用是当前面的某一项验证失败后,直接终止后续所有验证逻辑,避免闭包在ID不存在的场景下运行:

'category' => ['nullable', 'bail', 'exists:categories,id', function ($attribute, $value, $fail) {
    $category = Category::where('id', $value)->first();
    if($category->vcard!= $this->vcard->phone_number)
    {
       $fail('The selected category is invalid.');
    }
}]

方案2:在闭包内增加空值判断

如果不需要终止后续验证,也可以直接在闭包内先判断查询结果是否存在,再执行后续校验逻辑:

'category' => ['nullable','exists:categories,id', function ($attribute, $value, $fail) {
    $category = Category::where('id', $value)->first();
    if (!$category || $category->vcard!= $this->vcard->phone_number)
    {
       $fail('The selected category is invalid.');
    }
}]

内容的提问来源于stack exchange,提问作者Gonçalo Bastos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:06:10