I need to have the current found controller and action in a middleware, so that I can do some authentication. But I found it impossible, because the pipe is like Middleware1 -> Middleware2-> do the dispatching -> controller@action() -> Middleware2 -> Middleware1.
Therefore before the dispatching, I cannot get the route info. It is definitely not right to do it after the $controller->action().
I did some research and found this.
$allRoutes = $this->app->getRoutes();
$method = \Request::getMethod();
$pathInfo = \Request::getPathInfo();
$currentRoute = $allRoutes[$method.$pathInfo]['action']['uses'];
But this does not work when visiting URI like app/role/1
, because $allRoutes
only have index of app/role/{id}
instead of app/role/1
.
Is there any workaround about this?
I found the correct answer to this problem. I missed one method named routeMiddleware()
of Application
. This method registers the route-specific middleware which is invoked after dispatching. So Just use $app->routeMiddleware()
to register you middleware. And get the matched route info by $request->route()
in your middleware.