Reputation: 706
I am doing validation this way.
$rules = [
'email'=> 'required|regex:/^.+@.+$/i|unique:tab_example,email,'.$this>get('example_id').',example_id'
];
return $rules;
However, I am not getting success.
The error informs that
the email already exists
What I want is that if the email already exists and is from the same user does not need to inform that the email already exists.
I do not know what the problem is in my code.
Upvotes: 3
Views: 754
Reputation: 10111
Sometimes, you may wish to ignore a given ID during the unique check.
For example, consider an "update profile" screen that includes the user 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 can use like:
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
Upvotes: 2
Reputation:
Try This way
$rules = [
'email'=> ['required', 'email', \Illuminate\Validation\Rule::unique('tab_example', 'email')->whereNot('example_id',$this->get('example_id'))]
];
Upvotes: 1
Reputation: 3065
Just use
$this->route('example_id')
instead of
$this>get('example_id')
And if you use resource route then use $this->route('user').
$rules = [
'email'=> 'required|regex:/^.+@.+$/i|unique:tab_example,email,'.$this->route('example_id').',example_id'
];
return $rules;
Upvotes: 0
Reputation: 2009
You can use
'email' => "required|email|unique:users,email,{$id},id",
The id should be replaced with the primary key column name of the table you use for the unique check. The {$id} should be defined before $rules
array like:
$id = $request->route('user')
Upvotes: 3
Reputation: 426
Try this
'email' => Rule::unique('users')->ignore($user->id, 'user_id');
Read Under the Section Forcing A Unique Rule To ignore A given Field
Upvotes: 1