如何在laravel中设置中间件

时间:2015-09-20 21:14:14

标签: php laravel laravel-5 laravel-middleware

所以我有我的auth中间件,它在Http/Kernel.php注册为:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];

接下来,我对Authenticate类中的中间件句柄函数进行了更改:

public function handle($request, Closure $next)
{
    if ($this->auth->check()) {
        $user = $this->auth->user();

        $currentDateTime     = strtotime('Y-m-d H:i:s');
        $tokenExpirationTile = strtotime($user->token_expiration);

        if ($currentDateTime <= $tokenExpirationTile) {
            return $next($request);
        } else {
            $this->auth->logout();
            redirect('home/login')->with('message', 'Your session has expired. Please login in again');
        }
    } else {
        redirect('home/login')->with('message', 'Please login before attempting to access that');
    }
}

最后我创建了路线:

Route::get('home/dashboard', 'HomeController@dashboard', ['middleware' => 'auth']);

我可以访问此路线,但作为非签名用户,我应该重定向。

当我通过dd()函数中的handle时,没有任何反应。

如何在此路线上运行此方法?

另外,对于需要在每个操作请求之前进行身份验证的其他控制器,您如何说:&#34;在每个操作之前,运行此方法。&#34;在rails中我会做before_action :method_name

1 个答案:

答案 0 :(得分:1)

关于问题的第二部分,请参阅文档,了解如何将中间件应用于控制器和路由中的特定操作:

http://laravel.com/docs/master/controllers#controller-middleware http://laravel.com/docs/master/routing#route-group-middleware

对于第一部分,您是否尝试过从终端运行'composer dump-autoload'?