【问题标题】:How to validate if an attribute belongs to a certain user如何验证属性是否属于某个用户
【发布时间】:2022-01-05 05:42:03
【问题描述】:

大家好,我正在尝试验证该类别是否属于某个用户,我已经尝试过了,但是当我输入一个不存在的值时出现错误。我尝试了什么:

'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 100000,就会在邮递员上抛出这个错误:

我认为'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 validation


    【解决方案1】:

    解决此问题的一种简单方法是检查 $category 是否为空:

    if($category && $category->vcard != $this->vcard->phone_number) {
       $fail('The selected category is invalid.');
    }
    

    在 Eloquent 中使用 findfirst 时,如果模型存在则返回模型,如果不存在则返回 null


    或者,您可以对category 使用bail 验证规则:

    'category' => [
        'bail',
        '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.');
            }
        },
    ],
    

    这意味着如果exists 规则失败,甚至不会执行闭包。

    【讨论】:

    • “保释”工作得很好,我认为 laravel 是错误的(第一个验证规则失败)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2019-07-20
    • 2020-01-02
    • 2020-03-09
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    相关资源
    最近更新 更多