0

Hi I am using Middleware of Laravel 5 and what I am doing is I have middleware which is being used in few controllers, and each of my controllers has it's own configs, which I need to pass my middleware, how can I do that?

Hayk Aghabekyan
  • 1,087
  • 10
  • 19

1 Answers1

0

If you are using this Middleware in "Stack" (Defined at App/Http/Kernel.php in $middleware array), you don't have the $request->route() available.

BUT, if you are using it on routes.php file as middleware of a single route or group of routes, you can do this way:

Create a config file as you want, with config items named with same name of each route, then in your middleware you get route name and load proper configs.

Sorry if it's confuse, imagine this code:

Config/permissions.php

<?php 

return [
    // Route name here
    'user.index' =>
    // Your route options here
    [
        'option_a' => true,
        'option_b' => false,
    ],
    'user.edit' =>
    [
        'option_a' => true,
        'option_b' => true,
    ],
    /* ... */
];
?>

So in your middleware handle function you do something like this:

public function handle($request, Closure $next)
{
    $route = $request->route()->getName();

    /* Check if there is a permission to this route in config file */
    if (\Config::get("permissions.{$route}")) {
        $options = \Config::get("permissions.{$route}");
        /* Here will be your options by route */
        /* Now it's up to you do what you want */

    } else {
        /* If not, use default options */
    }

    return $next($request);
}

BTW, I recommend you using Laracast Discuss foruns:

www.laracast.com/discuss

Elias Soares
  • 9,884
  • 4
  • 29
  • 59