2016-05-23 44 views
0

Laravel認證附加條件,該文檔顯示,我可以給認證查詢添加更多的條件,像這樣:也與其他模型中使用Laravel的5.2認證

指定附加條件

如果你願意,你除了用戶的電子郵件和密碼以外,還可以向認證查詢添加額外的條件。例如,我們可以驗證用戶標記爲「主動」:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) { 
    // The user is active, not suspended, and exists. 
} 

在我的情況,我想設置其住在另一許多一對多洋洋灑灑型號的條件:

class Account extends Model 
{ 
    public function users() { 
     return $this->belongsToMany('App\User', 'account_users'); 
    } 
} 
class User extends Model implements AuthenticatableContract 
{ 
    public function accounts() { 
     return $this->belongsToMany('App\Account', 'account_users'); 
    } 
} 

有它雖然中間件通過一個帳戶id和訪問它是這樣的:

$request->account

如何實現東北當它涉及一個相關模型時,它是否具有條件?我只是不知道如何使用ORM關係。任何幫助指向正確的方向非常感謝!

+0

你可以簡單地實現在同這種邏輯/檢查,如果在您使用驗證::嘗試聲明()。您可以檢查相關模型(假設它是這種情況下的帳戶)$ request-> user() - > accounts() - > wherePivot('account_id',$ request-> account); –

+0

@CanCelik你的意思是作爲'if'中的單獨條件嗎?不是'attempt()'的'credentials'參數的一部分嗎? – greener

+0

沒錯。 try()方法有第三個選項,您可以在其中設置false,以便在其他條件不符合時不會記錄用戶。 –

回答

0

如果你想利用Eloquent的關係,不幸的是,你可能需要在'if'控制結構中添加另一個條件。直到你的Auth :: attempt()完成 - 沒有Auth :: user()對象,並且你需要該對象用於ORM。

因此,你可以這樣做:

if (Auth::attempt(['email' => $email, 'password' => $password])) { 
    // Your extra conditions for accounts, just a couple of examples 
    if (count(Auth::user()->accounts) == 0) Auth::logout(); 
    if (! Auth::user()->accounts()->active()->get()) Auth::logout(); 
}