Lumen 角色中间件缺少参数
Posted
技术标签:
【中文标题】Lumen 角色中间件缺少参数【英文标题】:Lumen role middleware missing argument 【发布时间】:2016-03-20 03:27:07 【问题描述】:我是 Lumen 的新手,我正在尝试通过 Lumen 文档中的示例让角色中间件工作: http://lumen.laravel.com/docs/middleware#middleware-parameters
但是一旦我像这样将中间件添加到路由中:
$app->get('/', ['middleware' => 'role:editor', 'uses' => 'IndexController@index']);
我得到错误:
at Application->Laravel\Lumen\closure('2', 'Missing argument 3 for App\Http\Middleware\RoleMiddleware::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([
Illuminate\Cookie\Middleware\EncryptCookies::class,
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
Illuminate\Session\Middleware\StartSession::class,
Illuminate\View\Middleware\ShareErrorsFromSession::class,
Laravel\Lumen\Http\Middleware\VerifyCsrfToken::class,
App\Http\Middleware\RoleMiddleware::class
]);
App\Http\Middleware\RoleMiddleware.php:
<?php
namespace App\Http\Middleware;
use Closure;
class RoleMiddleware
public function handle($request, Closure $next, $role) // <-line 17
if (! $request->user()->hasRole($role))
// Redirect...
return $next($request);
希望有人能帮忙
【问题讨论】:
显示 RoleMiddleware 类 添加了 RoleMiddleware 类 【参考方案1】:根据错误,我了解到您没有在 handle()
中提供参数,即第三个参数。
您的handle()
应该如下所示。
public function handle($request, Closure $next, $role)
第三个参数$role
根据您的代码存储值editor
【讨论】:
奇怪的是它完全一样的“public function handle($request, Closure $next, $role)”【参考方案2】:似乎您必须将中间件注册为 RouteMiddleware 所以而不是:
$app->middleware([
Illuminate\Cookie\Middleware\EncryptCookies::class,
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
Illuminate\Session\Middleware\StartSession::class,
Illuminate\View\Middleware\ShareErrorsFromSession::class,
Laravel\Lumen\Http\Middleware\VerifyCsrfToken::class,
App\Http\Middleware\RoleMiddleware::class
]);
必须是:
$app->middleware([
Illuminate\Cookie\Middleware\EncryptCookies::class,
Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
Illuminate\Session\Middleware\StartSession::class,
Illuminate\View\Middleware\ShareErrorsFromSession::class,
Laravel\Lumen\Http\Middleware\VerifyCsrfToken::class,
]);
$app->routeMiddleware([
"role" => App\Http\Middleware\RoleMiddleware::class
]);
然后它就可以正常工作了!
【讨论】:
以上是关于Lumen 角色中间件缺少参数的主要内容,如果未能解决你的问题,请参考以下文章