Get current route action name from middleware in laravel 5

laravel, laravel-5

Solution

You cannot get the route action name if the router has not yet been dispatched. The router class has not yet done its stuff - so you cannot do `$router->request()` - it will just be null.

If it runs as routeMiddleware as `$routeMiddleware` - then you can just do `$router->request()`

You can get the URI string in the middleware before the router has run - and do some logic there if you like: `$request->segments()`. i.e. that way you can see if the URI segment matches a specific route and run some code.

Edit:

One way I can quickly think of is just wrap all your routes in a group like this:

$router->group(['middleware' => 'permissionsHandler'], function() use ($router) {
            // Have every single route here
});

Problem

I have a middleware like this: ``` <?php namespace App\Http\Middleware; use App\Contracts\PermissionsHandlerInterface; use Closure; class PermissionsHanlderMiddleware { public $permissionsHandler; function __construct(PermissionsHandlerInterface $permissionsHandler) { $this -> permissionsHandler = $permissionsHandler; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $routeAction = $request->route()->getActionName(); /* do some operations */ return $next($request); } } ``` but `$request->route()` always returns `null`, I think its because the router hasn't been dispatched with the request. Note: I added my middleware to `Kernal.php` global middlewares to run before each request as the following ``` protected $middleware = [ . . . 'App\Http\Middleware\PermissionsHanlderMiddleware', ]; ``` I want to get route action name before the execution of `$next($request)` to do some permission operations. How can i do this ?

Original source