2015-11-28 51 views
1

我的自定義中間件存在問題。它不起作用。我已經在Kernel.php中註冊了它,只在$ routeMiddleware中註冊。這裏是我的代碼:Laravel 5中間件不起作用

/** 
* The application's route middleware. 
* 
* @var array 
*/ 
protected $routeMiddleware = [ 
    'auth' => \App\Http\Middleware\Authenticate::class, 
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 
    'test' => \App\Http\Middleware\TestMiddleware::class 

]; 
} 

這是我的控制器代碼:

/** 
* Middleware Activated 
*/ 
public function __constructor() 
{ 
    $this->middleware('test'); 
} 

,這裏是我的自定義中間件代碼:

protected $auth; 
/** 
* Handle an incoming request. 
* 
* @param \Illuminate\Http\Request $request 
* @param \Closure $next 
* @return mixed 
*/ 
public function handle($request, Closure $next) 
{ 
    if (!$this->auth->check()) 
    { 
     return redirect('/'); 
    } 
    return $next($request); 
} 

當我註銷並鍵入URL

profile/21

它顯示了用戶的個人資料,我用id 21.我想阻止與中間件,但它不會爲我工作。

有沒有人有一個想法如何做到這一點或錯誤在哪裏?

+0

我的文件看起來像: /** * 應用的路線中間件。 * * @var陣列 */ 保護$ routeMiddleware = [ 'AUTH'=> \應用\ HTTP \中間件\身份驗證::類, 'auth.basic'=> \照亮\驗證\中間件\ AuthenticateWithBasicAuth :: class, 'guest'=> \ App \ Http \ Middleware \ RedirectIfAuthenticated :: class, 'test'=> \ App \ Http \ Middleware \ TestMiddleware :: class ]; –

回答

1

爲了確保中間件是否被觸發,在中間件的句柄函數中放置了類似die('middleware triggerd');的東西。

我注意到你有function __constructor()而不是function __construct()
這可能是問題所在。

如果它引發的中間件,但你仍然有同樣的問題嘗試更換:
if (!$this->auth->check())if (!\Auth::check())

+0

我把dd(),但它沒有觸發。我不想在路由文件中使用它,因爲我認爲在控制器中使用它更優雅。我找不到我錯在哪裏。 我用Auth :: check()嘗試過,但仍然不起作用。 –

+0

也許,但我使用Route :: resource('profile','ProfileController');我只想使用,除了在特定功能上使用該中間件。 –

+0

謝謝你,那是問題所在。 –