2014-11-05 21 views
5

我如何在Laravel中注入Auth依賴項?Laravel:Dependency Inject Auth

像這樣:

public function __construct(Auth $auth) 
    { 
     $this->auth = $auth; 

    } 

如果我這樣做,那麼這不起作用:如果要注入驗證

public function __construct(Illuminate\Auth\AuthManager $auth) 
{ 
    $this->auth = $auth; 
} 

回答

6

你應該輸入提示Illuminate\Auth\AuthManager ,你實際上需要注入這個類:

use Illuminate\Contracts\Auth\Guard; 

,將解決你定義內的一切:

config/auth.php 

如果你想擴展驗證,你可以這樣做,但僅適用於:

  1. 衛隊驅動程序是保護類 - 它需要實現Guard或StatefulGuard接口。

  2. Provider是UserProvider類 - 它需要實現UserProvider接口。

在Laravel /流明標準驗證衛隊司機:

  1. SessionGuard
  2. TokenGuard

標準驗證UserProviders在Laravel /流明是:

  1. EloquentUserProvider
  2. DatabaseUserProvider

更多有關擴展驗證你有正式Laravel文檔。見下面的鏈接:

https://laravel.com/docs/5.0/extending#authentication

這是我在我的控制器中的代碼,它正在像一個魅力:

public function createToken(Request $request, Guard $guard) 
    { 
//  return 'in progress...'; 
    } 
用於擴展驗證類

最好的做法是在的ServiceProvider啓動()方法。

希望這會有所幫助!

乾杯。

+0

這沒有奏效。當我運行一個測試... $ user_type = $ this-> auth-> user() - > user_type; ...失敗 – 2014-11-05 15:10:53

+0

您有用戶會話嗎?因爲試圖在沒有用戶會話的情況下獲得'$ this-> auth-> user() - > user_type',肯定會拋出一個'嘗試獲取非對象屬性的異常。 – Bogdan 2014-11-05 15:17:06

+0

嗨,道歉!我試圖單元測試一個控制器,上面的代碼導致錯誤。最初我只是使用Auth的門面模式,但這導致了同樣的問題。 – 2014-11-05 15:40:04

3

$user_type = Auth::user()->user_type;