如何验证属性是否属于某个用户
How to validate if an attribute belongs to a certain user
伙计们,我正在尝试验证该类别是否属于某个用户,我已经尝试过了,但是当我输入一个不存在的值时出现错误。我尝试了什么:
'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
}
解决此问题的一个简单方法是检查 $category
是否为空:
if($category && $category->vcard != $this->vcard->phone_number) {
$fail('The selected category is invalid.');
}
当find
或first
与Eloquent一起使用时,模型存在则返回,模型不存在则返回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
规则失败,闭包甚至不会被执行。
伙计们,我正在尝试验证该类别是否属于某个用户,我已经尝试过了,但是当我输入一个不存在的值时出现错误。我尝试了什么:
'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
}
解决此问题的一个简单方法是检查 $category
是否为空:
if($category && $category->vcard != $this->vcard->phone_number) {
$fail('The selected category is invalid.');
}
当find
或first
与Eloquent一起使用时,模型存在则返回,模型不存在则返回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
规则失败,闭包甚至不会被执行。