0

I'm making a user CRUD and I use Requests to validate the methods of my controllers. In my update method I have a validator with the following rules:

return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', function($attribute, $value){
                // How to validate?
            }],
            'roles' => ['required', 'array', 'in:admin,manager,employee,client']            
        ]

I'm trying to validate, when updating a user if there is another user with the same e-mail, but I couldn't find a way to do that.

This is the model I receive (it's a rest api). The user ID comes in as a URL parameter:

{
    "name":"Andre Luiz",
    "email": "andredx@xxxxxxxx.com",
    "roles": ["admin"]
}

How can I do this validation?

André Luiz
  • 6,642
  • 9
  • 55
  • 105
  • Possible duplicate of [Laravel update model with unique validation rule for attribute](https://stackoverflow.com/questions/22405762/laravel-update-model-with-unique-validation-rule-for-attribute) – Namoshek Dec 08 '18 at 15:46

2 Answers2

0

you can validate by unique:users .. where users is the table where you have email

rakesh shrestha
  • 1,335
  • 19
  • 37
0

Using only unique|users foes not work as expected. This is how I achieved it:

return [
    'name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'. Auth::user()->id],
    'roles' => ['required', 'array', 'in:admin,manager,employee,client']            
];
André Luiz
  • 6,642
  • 9
  • 55
  • 105