首页 > 解决方案 > 有什么方法可以使用 laravel 从单独表中的两列中对用户进行身份验证?

问题描述

我有一个流程,我根据提供的emailprovider_id(用于社交登录)对用户进行身份验证。现在我provider_id在同一张表中有列users。以下脚本可以正常工作以对用户进行身份验证。

$loginAttempt = User::where([
    ['provider_id', '=', $request->provider_id],
    ['email', '=', $request->email]
])->first();
if($loginAttempt !== null){
    Auth::login($loginAttempt);
    if (!Auth::check()){
        ...
    }else{
        ...
    }
}

但是通过这种方式,我无法为一个用户存储多个社交登录信息。我将分成两张桌子。第二个是social_login我添加了两列user_idprovider_id.

现在我想基于email和验证用户,provider_id但现在这些在两个不同的表中。我尝试了相同的脚本并进行了一些小改动,但它不起作用。

有人可以指导我吗,我该怎么做。我真的很感激。

太感谢了。

标签: phplaravel

解决方案


我假设您的意思provider_id是现在在您的social_login表中并且 user_id在您的social_login表中与您的用户表中的用户 ID 有hasMany()关系(意味着用户可以有多个 provider_id)?在这种情况下,您可以执行以下操作:

$user = User::where(['email', $request->email])->first();  //check if the email exists
if(!$user){  //return error if not
    return back()->withError('Email is invalid.');
}
//lookup the provider_id for the user
$loginAttempt = $user->provider_ids->where(['provider_id', $request->provider_id])->first();  
if($loginAttempt){
    Auth::login($loginAttempt);
    if (!Auth::check()){
        ...
    }else{
        ...
    }
}

编辑:

为清楚起见,您的 User 模型将具有以下功能:

public function provider_ids()
  {
    return $this->hasMany('App\ProviderID');
  }

您的 social_login 表可能如下所示:

public function up()
{
  Schema::create('social_login', function(Blueprint $table)
  {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');
    $table->string('provider_id');
    $table->timestamps();
  });
}

推荐阅读