首页 > 解决方案 > 电子邮件唯一验证

问题描述

我的问题是更新用户资料!例如,作为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."
        ]
    }
}

这是我的数据库结构:

在此处输入图像描述

标签: phplaravel

解决方案


您可以为此编写自定义验证

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.');
                }

            }

        }]
        ];
}

推荐阅读