vitorarjol's avatar

How to get the 2 param for a Middleware?

Hi guys! I'm trying to build a VerifyPermissionMiddleware, but I can't get to work multiple parameters..

Here is the code:

#The Middleware
class VerifyPermissionMiddleware
{
    public function handle($request, Closure $next, $permissions)
    {
        return $next($request);
    }
}
#My route
get('users', ['middleware' => 'verify.permission:a,c,b']);

If I run a dd($permissions) in my middleware I just get the first parameter :(

Any clues of what am I doing wrong?

0 likes
10 replies
pmall's avatar
#The Middleware
class VerifyPermissionMiddleware
{
    public function handle($request, Closure $next, $permission1, $permission2, $permission3)
    {
        return $next($request);
    }
}
1 like
phildawson's avatar
Level 26

@vitorarjol You can have an array if you wish

public function handle($request, Closure $next, ...$permissions)
1 like
kfirba's avatar

@vitorarjol You can do something that I've done in my project lately (for PHP <= 5.5):

public function handle($request, Closure $next, $permissions)
{
    $permissions = preg_split('/(\s)*\|(\s)*/', $persmissions);

    // now the $permissions holds an array of the permissions
}

// in your middleware calling:
get('users', ['middleware' => 'verify.permission:a|b|c|d|e | f |g |h']);
// as you can see you may have any amount of spaces between the pipes for conveniency.

Also, if you want to get away with it without using Regex you can do something like this:

public function handle()
{
    $permissions = func_get_args();
    $request = array_shift($permissions);
    $next = array_shift($permissions);

    // now the $permissions holds an array of the permissions
}

For PHP >= 5.6 you can indeed use it as you marked:

public function handle($request, Closure $next, ...$permissions)
3 likes
vitorarjol's avatar

Good solution @kfirba, thanks for the contribution. In that case I have php 5.6 on the server, but certainly someone will find that question and use your answer. \o

kfirba's avatar

@vitorarjol That's why I posted it, for future reference :) Also, I've added another method to do that in PHP version prior to 5.6.

1 like
rulatir's avatar

The spread operator solution makes it possible to send multiple parameters to middleware, but each of these parameters must be a simple value that is parseable from a string. This is still too limiting for me.

Is there a way to pass multiple parameters to a middleware, each of those parameters being a complex data type like object or array or even callable?

Please or to participate in this conversation.