[英]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.