Lumen role middleware missing argument

- 1 answer

Ad

I'm new to Lumen and i am trying to get the role middleware to work from an example in the Lumen docs: http://lumen.laravel.com/docs/middleware#middleware-parameters

But as soon as i add the middleware to the route like so:

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

I get the error:

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

When i remove the middle ware everything works as expected

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

In 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);
    }
}

Hope someone can help

Ad

Answer

Ad

Seems that you have to register the Middleware as RouteMiddleware so instead of:

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

it has to be:

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

Then it works fine!

Ad
source: stackoverflow.com
Ad