【问题标题】:Laravel 5 Middleware Doesn't workLaravel 5 中间件不起作用
【发布时间】:2015-11-28 13:30:08
【问题描述】:

我的自定义中间件有问题。它不起作用。我已经在 Kernel.php 中注册了它,仅在 $routeMiddleware 中。这是我的代码:

/**
 * 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);
}

当我退出并输入网址时

个人资料/21

它向我显示了 id 为 21 的用户的个人资料。我想用中间件防止这种情况发生,但它对我不起作用。

有没有人知道如何做到这一点或错误在哪里?

【问题讨论】:

  • 我的文件看起来像: /** * 应用程序的路由中间件。 * * @var 数组 */ 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 ];

标签: laravel routes kernel middleware


【解决方案1】:

要确保中间件是否被触发,请在中间件的句柄函数中添加 die('middleware triggerd'); 之类的内容。

我注意到您使用的是 function __constructor() 而不是 function __construct()
这可能是问题所在。

如果它确实触发了中间件,但您仍然遇到同样的问题,请尝试将:
if (!$this->auth->check()) 替换为 if (!\Auth::check())

【讨论】:

  • 我放了 dd() 但它没有触发。我不想在路由文件中使用它,因为我认为在控制器中使用它更优雅。我找不到我错的地方。我试过 Auth::check() 但还是不行。
  • 也许,但我使用 Route::resource('profile', 'ProfileController');我只想在特定功能上使用该中间件。
  • @HerilMuratovic 很高兴为您提供帮助!
  • 我有同样的问题,我在数据库中有一个字段,在用户模型上,名为“is_admin”,中间件工作正常;但是,当我将其更改为“角色”时,它现在停止工作,它只允许任何人访问受保护的页面。
猜你喜欢
  • 2015-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多