Laravel 5.5检查用户有三个PARAM存在于两个表

问题描述 投票:0回答:2

我开发寄存器模块,我想查一下我的电子邮件,nationalCode或移动网络应用程序的注册用户,我有两个表,用户和用户信息,我存储电子邮件的用户表,我储存nationalCode和移动用户信息表,我想编写代码来检测,如果用户的电子邮件或nationalCode或移动在我的两个表存在,我显示警告文字用户已经在我的网站注册,请帮我做这个工作,

我用步的形式和我写的AJAX调用方法做这个任务,请注意,有可能格兰用户有三场比赛,或只是其中之一匹配感谢您的帮助:)

下面是Ajax代码:

    $.ajax({
    url: url',
    type: 'POST',
    data: {
        _token: CSRF_TOKEN ,
        code:code,
        email:email,
        mobile:mobile,
    },
    dataType: 'JSON',
    success:function(data) {
        //return data
    }
});

这里是我的方法是控制

public function checkUser(Request $request)
{
    $email = $request->email;
    $mobile = $request->mobile;
    $code = $request->code;

    //here the query to detect user exist with three params
}
php laravel laravel-5 registration
2个回答
0
投票

比方说,你有你的关系定义如下:

class User extends Model
{
    public function info()
    {
        return $this->hasOne(UserInfo::class); 
    }
}

class UserInfo extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class); 
    }
}

......那么,可以检查该用户是否存在像这样的东西。

$user = User::where('email', $request->email)
    ->whereHas('info', function($query) use($request) {
        $query->where('mobile', $request->mobile)
            ->where('code', $request->code); 
    })
    ->exists();

// user will be false if there's no record matching those parameters

另外,如果你没有你的关系定义,那么你可能需要做这样的事情吧。

$user = User::where('email', $request->email)->exists();
$info = UserInfo::where([
    'mobile' => $request->mobile,
    'code'   => $request->code
])->exists(); 

if($user && $info) {
    // user exists 
}

我还是喜欢去与选项的:)


0
投票

如果你把唯一的标识符在你的表,数据库会自动检测并返回错误,但它不是很好的做法,让数据库来处理,

如果你想用雄辩那么查询应该是这样的

public function checkUser(Request $request)
{
    $email = $request->email;
    $mobile = $request->mobile;
    $code = $request->code;
    $user = User::query()->where('email', '=', $email)->orWhere('mobile','=',$mobile)
            ->orWhere('code', '=',$code)->get();
    if($user) {
     // User already exits
       return;
    }
}

但是,这验证了我也不好,更好的是使用Laravel请求https://laravel.com/docs/5.7/validation#form-request-validation

要生成自定义请求使用此命令(PHP的工匠制作:要求RequestName)

public function rules()
{
    return [
        'title' => 'required|unique:users',
        'mobile' => 'required|unique:users',
        'code' => 'required|unique:users',
    ];
}

使用的要求很简单

public function checkUser(YourCustomRequest $request)
{
    // Laravel will take care of all fields and check them if they exist in the database
}
© www.soinside.com 2019 - 2024. All rights reserved.