Hy guys I am trying to validate if the category, belongs to a certain user, I have tryed this but I getting an error when I enter a non existing value. What I tryed:
'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.');
}
}]
So this works when I entered a valid category, but if I entered a wrong categry, for example category id 100000 that doesnt exists, throws me this error, on postman:
I thought that the 'exists:categories,id'
will fix me, the non existing ids.
Works:
{
"payment_reference": "[email protected]",
"payment_type": "PAYPAL",
"type": "D",
"value": 10,
"description": "Teste",
"category": 500
}
Not working:
{
"payment_reference": "[email protected]",
"payment_type": "PAYPAL",
"type": "D",
"value": 10,
"description": "Teste",
"category": 1000000
}
CodePudding user response:
A simple way to fix this would be to check if $category
is null or not:
if($category && $category->vcard != $this->vcard->phone_number) {
$fail('The selected category is invalid.');
}
When using find
or first
with Eloquent, the model will be returned if it exists and null
will be returned if it doesn't.
Alternatively, you could use the bail validation rule for category
:
'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.');
}
},
],
This will mean that if the exists
rule fails the closure won't even be executed.