php - Email Unique Validation
Get the solution ↓↓↓My problem is updating User profile! For example, as a user with ID "1", request is sent to the server for an update If user send a new email address to the server , update will be done! , but if user send the current e-mail address ( in database exists), The Server should not do the update!, Also, consider the user with ID number 2, but this time, if user with id 2 .accidentally has send email address of user 1, server doesn't update the email address and return to the user this validation error : "This email has already been Taken by another user"
i'm tying to make best validation role for Profile's Table
Profile Request :
public function rules()
{
return[
"avatar_src"=>"string",
"address"=>"string",
'email' => Rule::unique('profiles')->ignore($this->user()->id),
];
}
I have written this, but I'm facing this error in any case!
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email has already been taken."
]
}
}
this is my database Structure :
Answer
Solution:
You can write custom validation for that
public function rules()
{
return[
"avatar_src"=>"string",
"address"=>"string",
'email' => function ($attribute, $value, $fail) {
if(isset($this->user()->id)&&!empty($this->user()->id)){
$profile=Profile::where('email',$value)->where('user_id','!=',$this->user()->id)->first();
if($profile){
$fail('The '.$attribute.' is invalid.');
}
}
},
];
}
Updated
public function rules()
{
return[
"avatar_src"=>"string",
"address"=>"string",
'email' =>["email", function ($attribute, $value, $fail) {
if(isset($this->user()->id)&&!empty($this->user()->id)){
$profile=Profile::where('email',$value)->where('user_id','!=',$this->user()->id)->first();
if($profile){
$fail('The '.$attribute.' is invalid.');
}
}
}]
];
}
Answer
Solution:
Your validation is Ok, you have to setup an "email verification process" and erase email field if verification does not succeed.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non-numeric value encountered in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.