2015-12-14 41 views
2

我是新來的流明,我試圖讓角色中間件從一個例子流明文檔工作: http://lumen.laravel.com/docs/middleware#middleware-parameters流明角色中間件缺少參數

但只要我中間件添加到路由像這樣:

$app->get('/', ['middleware' => 'role:editor', 'uses' => '[email protected]']); 

我得到的錯誤:

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' => '[email protected]']); 

在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 
]); 

應用程序\ HTTP \中間件\ 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); 
    } 
} 

希望有人能幫助

+0

顯示RoleMiddleware類 –

+0

添加了RoleMiddleware類 – Peter

回答

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 
]); 

然後它工作正常!

0

通過我的理解是錯誤您沒有在您的handle()即第三個參數中提供參數。

您的handle()應該看起來像這樣。

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

第三個參數$role存儲值editor按你的代碼

+0

奇怪的是它完全相同的「公共函數句柄($ request,Closure $ next,$ role)」 – Peter