Laravel 5.1 Pass middleware parameters as array

Laravel has added support for middleware parameter since version 5.1 . So it is nice that we can pass middleware parameter from Routes.php or from controller. Let’s see an example.


Route::get('test',['middleware'=>'hasAccess:Admin', function(){
 return "Access granted for this operation"; 
}]);

or in controller constructor

//Other stuff in controller
public function __construct()

{

    $this->middleware('hasAccess:admin');

}

//Other stuff in controller

and in middleware handle function you can catch argument which is passed as mentioned below:

public function handle($request, Closure $next, $roleName)
{

    if($roleName=="Admin")

        return $next($request);

    else

        return redirect()->guest(route('login'));

}

You can see that our route is protected with admin role. Means user with admin role can only access test route in our application.

But what if i have to check two roles or three roles. Should i have to catch three variables in handle method of hasAccess middleware. You can but there is a better way . As PHP 5.6 released they provide variable function argument feature so you can use it to pass dynamic argument and treat it as array.

See below code example to demonstrate passing array in middleware as argument.

Route::get('/admin',['middleware'=>'hasAccess:Admin,Registered', function () {
     return "Access is granted for this operation";

}]);

and in Middleware handle function

public function handle($request, Closure $next, ...$params)
{

    print_r($params);

    exit;

    return $next($request);
}

You will get below output.

Array ( [0] => Admin [1] => Registered )

So in this way you can pass array as middle ware parameter.

Advertisements

16 thoughts on “Laravel 5.1 Pass middleware parameters as array

  1. I have this error
    exception ‘Symfony\Component\Debug\Exception\FatalErrorException’ with message ‘syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE)’

    Like

  2. Thanks You,
    Ahesan bhai,

    I was looking for passing multiple parameters in laravel middleware, So I found by reading your post and set three dots[…] before of parameter in middleware and it worked. Really good work…keep it up

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s