Laravel中间件在某些资源路径上不起作用


Laravel Middleware not working on some resource route

我正在学习一个关于设置访问级别限制的教程:

https://gist.github.com/amochohan/8cb599ee5dc0af5f4246

我能够以某种方式让它发挥作用,但我需要做一些教程中没有的事情。

前提是我已经遵循了教程。我已经设置了这个资源路线:

Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['Administrator']], function()
{
    Route::resource('changeschedule', 'ChangeScheduleController', ['only' => ['index'], 'except' => ['create']]);
});

所以我想要的只是将roles中间件应用于资源路由,但对于该资源中的特定路由,我只想应用于index,所以我有了上面的路由。

当我去:

http://localhost/hrs/public/changeschedule

它运行良好,中间件roles运行良好。但当我去时,为什么会这样呢

http://localhost/hrs/public/changeschedule/create

我得到

NotFoundHttpException in RouteCollection.php line 161:

所以我有一个未找到的路线错误。为什么?但当我做时

Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['Administrator']], function()
{
    Route::resource('changeschedule', 'ChangeScheduleController');
});

然后它工作正常,但中间件应用于所有:

index, create, update, edit, delete

我希望它只在索引中。

我的代码:

Kernel.php

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

CheckRole.php

<?php namespace App'Http'Middleware;
use Closure;
class CheckRole{
    /**
     * Handle an incoming request.
     *
     * @param  'Illuminate'Http'Request  $request
     * @param  'Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Get the required roles from the route
        $roles = $this->getRequiredRoleForRoute($request->route());
        // Check if a role is required for the route, and
        // if so, ensure that the user has that role.
        if($request->user()->hasRole($roles) || !$roles)
        {
            return $next($request);
        }
        return response([
            'error' => [
                'code' => 'INSUFFICIENT_ROLE',
                'description' => 'You are not authorized to access this resource.'
            ]
        ], 401);
    }
    private function getRequiredRoleForRoute($route)
    {
        $actions = $route->getAction();
        return isset($actions['roles']) ? $actions['roles'] : null;
    }
}

您可以尝试这样做,创建一个构造函数并从中添加中间件,例如:

public function __construct()
{
    $this->middleware('auth');
    $this->middleware('roles:administrator', ['only' => ['index']]);  
}

阅读文档。

Update(中间件中的第三个参数::handle方法可以接受参数):

public function handle($request, Closure $next, $role)
{
    // $role will catch the administrator or whatever you pass
}

您也可以在我的博客(关于中间件)上查看这些示例/教程。