php - 电子邮件唯一验证
问题描述
我的问题是更新用户资料!例如,作为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."
]
}
}
这是我的数据库结构:
解决方案
您可以为此编写自定义验证
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.');
}
}
}]
];
}
推荐阅读
- android - 进行 rxJava 网络调用并根据响应在 UI 线程上推进工作的最佳方法是什么
- groovy - 从 Unetstack 中的路由表中删除路由
- wcf - WCF 从管道读取错误:管道已结束。(109, 0x6d)
- python-3.x - 元类的“__init_subclass__”方法在此元类构造的类中不起作用
- mysql - 如何选择其他查询中不存在的数据
- amazon-aurora - 无法从 SQL 客户端连接 Amazon Aurora Serverless
- .net-core - .net core 2.2 从 Main 写入 NLog,但不从控制器写入
- r - 从以“-”分隔的字符串中提取数字及其符号
- android - java.lang.IndexOutOfBoundsException: Index: 30, Size: 30 in onBindViewHolder() on Android
- python-3.x - 调用 __init__ 时尝试从 pandas DataFrame 继承时出错