Lumen角色中间件缺少参数



我是Lumen的新手,我正试图从Lumen文档中的一个示例中获得角色中间件:http://lumen.laravel.com/docs/middleware#middleware-参数

但一旦我把中间件添加到路由中,就像这样:

$app->get('/', ['middleware' => 'role:editor', 'uses' => 'IndexController@index']);

我得到错误:

at Application->LaravelLumen{closure}('2', 'Missing argument 3 for AppHttpMiddlewareRoleMiddleware::handle()', '/Users/peter/app/Http/Middleware/RoleMiddleware.php', '17', array('request' => object(Request), 'next' => object(Closure))) in RoleMiddleware.php line 17

当我删除中间软件时,一切都像预期的一样工作

$app->get('/', ['uses' => 'IndexController@index']);

在app.php中:

$app->middleware([
    IlluminateCookieMiddlewareEncryptCookies::class,
    IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
    IlluminateSessionMiddlewareStartSession::class,
    IlluminateViewMiddlewareShareErrorsFromSession::class,
    LaravelLumenHttpMiddlewareVerifyCsrfToken::class,
    AppHttpMiddlewareRoleMiddleware::class
]);

App\Http\Middleware\RoleMiddleware.php:

<?php
namespace AppHttpMiddleware;
use Closure;
class RoleMiddleware
{
    public function handle($request, Closure $next, $role) // <-line 17
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }
        return $next($request);
    }
}

希望有人能帮助

似乎您必须将中间件注册为RouteMiddleware,而不是:

$app->middleware([
    IlluminateCookieMiddlewareEncryptCookies::class,
    IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
    IlluminateSessionMiddlewareStartSession::class,
    IlluminateViewMiddlewareShareErrorsFromSession::class,
    LaravelLumenHttpMiddlewareVerifyCsrfToken::class,
    AppHttpMiddlewareRoleMiddleware::class
]);

必须是:

$app->middleware([
    IlluminateCookieMiddlewareEncryptCookies::class,
    IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
    IlluminateSessionMiddlewareStartSession::class,
    IlluminateViewMiddlewareShareErrorsFromSession::class,
    LaravelLumenHttpMiddlewareVerifyCsrfToken::class,
]);
$app->routeMiddleware([
    "role" => AppHttpMiddlewareRoleMiddleware::class
]);

那么它工作得很好!

根据错误,我理解您没有在handle()中提供参数,即第三个参数。

你的handle()应该是这样的。

public function handle($request, Closure $next, $role)

第三个参数$role根据您的代码

存储值editor

最新更新