php - 有什么方法可以使用 laravel 从单独表中的两列中对用户进行身份验证?
问题描述
我有一个流程,我根据提供的email
和provider_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_id
和provider_id
.
现在我想基于email
和验证用户,provider_id
但现在这些在两个不同的表中。我尝试了相同的脚本并进行了一些小改动,但它不起作用。
有人可以指导我吗,我该怎么做。我真的很感激。
太感谢了。
解决方案
我假设您的意思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();
});
}
推荐阅读
- apache-kafka - 在 KSQL 中加入两个(或更多)kafka 主题的最佳方法是从所有主题中发出变化?
- regex - vb.net中的字符串标记器?如何拆分多个符号多个变体?
- r - 运行堆叠栅格列表时如何解决错误问题?
- python - 尝试使用烧瓶在 MongoDB 中插入字段时出现身份验证错误
- docker - 如果我重新启动一个运行一些 pod 的节点会发生什么
- linux - 使用 pid 查找 TCP 连接
- sql - 将 SQL Server 查询转换为 Postgres 查询
- peoplesoft - 使用 Peoplesoft 数据元素生成 HTML 格式的电子邮件
- python - 如何从字符串键定义python常量
- continuous-integration - Artifactory 旧工件清理 (AQL) 并保留最新 3 个版本