[英]how to use auth upon more than 1 table in laravel
我的数据库中有3个表{
being : holds the id field of member, //for some reason i have to
member: holds member specific data, //like unique name password ...
email : holds emails for all users //for no duplication and some few more things
}
现在我希望用户登录他的
{unique name and password} or
{id and password} or
{email and password}
这听起来像是一个错误的结构。 您应该将用户数据(id,用户名,电子邮件,密码等)保存在一个表下。 然后,您可以将它们用作要关联的其他表中的外键。 表之间的关系可以帮助您更好地管理用户,并且效率更高。 此外,如果您遵循此结构,您将能够针对每个独特字段进行身份验证,例如:
Auth::attempt(array('id'=>$id,'password'=>$password)
此外,您现在应该扩展Auth类并使用您自己的逻辑进行身份验证。
编辑 :最好的方法是创建一个新表来保存多个电子邮件。让我们说你创建一个名为用户电子邮件的表。 该表将有3个字段,对于primary,id为auto自动增量,user_id为user.id的外键,user_email为将保存多个电子邮件的字段。 请注意,user_id字段不是唯一的,它只是一个索引。 您可能会得到以下结果:
以上代表id为1的用户的3封电子邮件。 现在,如果您希望能够使用任何这些电子邮件登录,您可以按以下方式执行:
//UserEmail represents the Eloquent model for the table that holds the user emails
$emailrow = UserEmail::where('email','=',Input::get('email')->get();
$id = User::find($emailrow->user_id);
Auth::attempt(array('id'=>$id,'password'=>Input::get('password));
我知道有时我们的客户所拥有的表格很奇怪,所以如果是这种情况,请创建一个单独的类来处理来自任何所需类型的登录:
class Logon {
public function loginViaEmail($email, $password)
{
if ($emailModel = Email::where('email', $email)->first())
{
return $this->login($emailModel->user_id, $password);
}
return false;
}
public function loginViaName($name, $password)
{
if ($memberModel = Member::where('name', $name)->first())
{
return $this->login($memberModel->user_id, $password);
}
return false;
}
public function loginViaId($id, $password)
{
if ($beingModel = Being::where('id', $id)->first())
{
return $this->login($beingModel->user_id, $password);
}
return false;
}
public function login($id, $password)
{
$user = Member::find($id);
if(Hash::check($password, $user->password))
{
Auth::loginUsingId($id);
return true;
}
return false;
}
}
login()
完成了将用户登录到应用程序的工作,就像Laravel在内部使用Auth::attempt()
,所以其他一切都将在此之后正常工作。
现在,您可以在控制器中执行此操作:
$logon = new Logon;
if ( ! $logon->loginViaEmail(Input::get('email'), Input::get('password')))
{
return "username or password invalid";
}
return "logged in successfully";
要么
...
if ( ! $logon->loginViaName(Input::get('name'), Input::get('password')))
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.