userBoEB
userBoEB

Reputation: 23

Validation of user email field during update

I am new to laravel.

Currently, I'm working on user table CRUD operations. I've no problems while create, delete and read. I want to update user email column with validation.

When I've made email field as unique, no problem while creating since it will work perfectly with no duplicate email fields.

Validation:

$this->validate($request,[
    'email' => 'required|unique:users'
],
$messages = [
        'required' => 'The :attribute field is required.',
        'unique' => 'The :attribute must be unique',
    ]
);

But, While updating the record, if email field is not changed and other changed, validation fails due to unique violation because of email is checked with record it self.

I want uniqueness in email field even if user email is changed.

Can anyone give me some suggestion to get out of this problem ?

Upvotes: 2

Views: 655

Answers (3)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

I think you can try this :

'email'     => Auth::check()
                ? 'required|email|unique:users,email,'.Auth::id()
                : 'required|email|unique:users,email',

Hope this help for you!!

Upvotes: 0

Anand Pandey
Anand Pandey

Reputation: 2025

Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address. You only want to throw a validation error if the user provides an e-mail address that is already used by a different user. To tell the unique rule to ignore the user's ID, you may pass the ID as the third parameter:

   'email' => 'unique:users,email_address,'.$user->id

Upvotes: 1

Jonathon
Jonathon

Reputation: 16283

What you want to do is ignore a specific user ID during the validation process. By passing an ID to ignore to your unique rule, Laravel will exclude that user when checking the uniqueness of the email address.

https://laravel.com/docs/5.4/validation#rule-unique

The format of the rule is:

unique:table,column,except,idColumn

And in your scenario you can use it like this:

[
    'email' => 'required|unique:users,email,' . $userId
]

Where the $userId in this scenario is the ID of the user you're updating. Usually, this will be present in your request so you should be able to access it from there. If the column you want to ignore is different from id you can add that as the next part of your rule:

'email' => 'required|unique:users,email,' . $userId . ',other_column'

An alternative, and more readable syntax for the unique rule in versions 5.3 and above is:

Rule::unique('users')->ignore($userId),

Upvotes: 3

Related Questions