Reputation: 184
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 :
Upvotes: 0
Views: 352
Reputation: 15319
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.');
}
}
}]
];
}
Upvotes: 1
Reputation: 1321
Your validation is Ok, you have to setup an "email verification process" and erase email field if verification does not succeed.
Upvotes: 0