Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to validate if an attribute belongs to a certain user

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:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I thought that the 'exists:categories,id' will fix me, the non existing ids.

Works:

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

Not working:

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading