Home > Back-end >  Passing options to middleware in Laravel?
Passing options to middleware in Laravel?

Time:07-18

I have the following in my controller:

public function __construct()
{
    $this->middleware('contactpermissionschecker', array(
      'requiredAccess' => array(
         'canEdit' => 1,
         'canDelete' => 1,
      )
    ));
}

My problem is that I don't know how to access "canEdit" and "canDelete" in the middleware here:

public function handle(Request $request, Closure $next)
{
    print_r($request->requiredAccess);
}

Above I'm just trying to print it out from the request, but that doesn't work. I also tried:

$this->options

But also, not there. Any ideas how to get these variables in middleware?

CodePudding user response:

try adding requiredAccess to handle method args.

public function handle(Request $request, Closure $next, $requiredAccess)
{
   print_r($requiredAccess);
}

CodePudding user response:

As i have gone through document and other articles, and noted down that laravel middleware do not support multidimentional and associative array. If you would like to pass parameter as array then you have to use | deliminator.

public function __construct()
{
    $this->middleware('contactpermissionschecker:canEdit|canAccess');
}

public function handle(Request $request, Closure $next, $requiredAccess)
{
   $requestData = explode("|", $requiredAccess);
   foreach ($requestData as $key => $value) {
      dd($value);
   }
}

  • Related