【问题标题】:How do I set up middleware in laravel如何在 laravel 中设置中间件
【发布时间】:2015-12-17 12:18:20
【问题描述】:

所以我有我的身份验证中间件,它在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']);

我可以访问这条路线,但作为未登录用户,我应该被重定向。

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

如何让它在这条路线上运行这个方法?

另外,当涉及到需要在每个操作请求之前进行身份验证的其他控制器时,您怎么说:“在每个操作之前,运行此方法。”在rails中我会做before_action :method_name

【问题讨论】:

  • 你的 dd() 在哪里?如果你把 $this->middleware('auth');在您的 HomeController 构造函数中。根据文档“但是,在控制器的构造函数中指定中间件更方便。”
  • @ExoticChimp 我只希望它适用于特定的控制器操作
  • 请查看我回答中的文档。你把它放在你的构造函数中: $this->middleware('auth', ['only' => ['dashboard']]);

标签: php laravel laravel-5 laravel-middleware


【解决方案1】:

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

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

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

【讨论】:

  • 使用 composer dump 自动加载,它什么也不做,它生成类映射但同样的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 2019-06-16
  • 2017-12-10
相关资源
最近更新 更多