多个中间件在相同的路由上有权限

Multiple middleware has permittion on same routes

我有多个中间件(学生、parent、管理员)并使用该中间件创建一些路由组。但是如果用户在任何一个组中并且属于任何那个中间件,则某些路由可以访问,但如果在其他中间件中则不能访问,例如老师。我在文档中使用了类似的东西:http://laravel.com/docs/5.1/routing#route-groups 但是当我放置一个路由时它可以工作,当使用另一个中间件添加另一个路由组时它不起作用。这可能吗?如何实现?

当我执行 php artisan 路由时,它给我一个错误

[Symfony\Component\Debug\Exception\FatalErrorException]
  Call to a member function inRole() on null

Laravel的路由中间件按照routes.php文件中的声明,一个一个执行。因此,如果其中一个通过抛出异常或返回一些响应来拒绝访问,则不会执行下一个中间件。

为了完成这项工作,您需要一个中间件来检查当前用户是否具有任何必需的角色。幸运的是,从 Laravel 5.1 开始,您可以将参数从 routes.php 文件传递​​给中间件(参见 http://laravel.com/docs/5.1/middleware#middleware-parameters), 所以你只需要一个中间件 class 来处理所有情况。

示例中间件 class 可能如下所示:

class HasAnyRole
{
  public function handle($request, Closure $next, $roles)
  {
    // Return Not Authorized error, if user has not logged in
    if (!$request->user) {
      App::abort(401);
    }

    $roles = explode(',', $roles);
    foreach ($roles as $role) {
      // if user has given role, continue processing the request
      if ($request->user->hasRole($role)) {
        return $next($request);
      }
    }
    // user didn't have any of required roles, return Forbidden error
    App::abort(403);
  }  
}

在您的Kernel.php中注册中间件:

protected $routeMiddleware = [
  'has_any_role' => 'App\Http\Middleware\HasAnyRole',
];

现在,在您的 routes.php 中,您可以将中间件应用于这样的组:

//this route is available only to users with role admin or author
Route::put('post/{id}', ['middleware' => 'has_any_role:admin,author', function ($id) {
    //
}]);

这应该可以解决问题,只需确保您的 User class 具有 hasRole 方法。