我的问题是更新用户资料! 例如,作为 ID 为“1”的用户,向服务器发送更新请求 如果用户向服务器发送新的电子邮件地址,更新将完成! , 但如果用户发送当前电子邮件地址(在数据库中存在),服务器不应进行更新!, 另外,考虑 ID 号为 2 的用户,但是这一次,如果 ID 为 2 的用户不小心发送了用户 1 的电子邮件地址,服务器不会更新电子邮件地址并向用户返回此验证错误: “此电子邮件已被其他用户接收”
我正在为 Profile's Table 提供最佳验证角色
个人资料请求:
public function rules()
{
return[
"avatar_src"=>"string",
"address"=>"string",
'email' => Rule::unique('profiles')->ignore($this->user()->id),
];
}
我已经写了这个,但无论如何我都面临这个错误!
{
"message": "The given data was invalid.",
"errors": {
"email": [
"The email has already been taken."
]
}
}
这是我的数据库结构:
答案 0 :(得分:1)
您可以为此编写自定义验证
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.');
}
}
},
];
}
更新
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.');
}
}
}]
];
}
答案 1 :(得分:0)
您的验证没问题,您必须设置“电子邮件验证过程”并在验证不成功时删除电子邮件字段。