I want to get the name of the current I route in a middleware class. Previously (in Slim 2.*) you could fetch the current route like so:
$route = $this->app->router->getCurrentRoute();
But this function has been removed in the 3.0 version of Slim. I've found the following code in the __invoke
method of Slim\App
:
// Get the route info
$routeInfo = $request->getAttribute('routeInfo');
/** @var \Slim\Interfaces\RouterInterface $router */
$router = $this->container->get('router');
// If router hasn't been dispatched or the URI changed then dispatch
if (null === $routeInfo || ($routeInfo['request'] !== [$request->getMethod(), (string) $request->getUri()])) {
$request = $this->dispatchRouterAndPrepareRoute($request, $router);
$routeInfo = $request->getAttribute('routeInfo');
}
This indicates that the current route is stored as the attribute routeInfo
in the Request
. But it seems that my custom middleware class is called before the attribute is set (by the $this->dispatchRouterAndPrepareRoute($request, $router);
method). Because calling $request->getAttribute('routeInfo')
resolves to NULL
.
So my question is; how can I get the current route (or the name of the route) from a middleware function/class?
Or should I just copy the piece of code above from Slim\App
?
For Slim3, here is an example showing you how to get routing information from within middleware, which is actually a combination of previous answers put together.
In my case, I wanted to add middleware that would ensure the user was logged in on certain routes, and redirect them to the login page if they weren't. I found the easiest way to do this was to use
->setName()
on the routes like so:Then if this route was matched, the
$routeName
in the middleware example will be"index"
. I then defined my array list of routes that didn't require authentication and checked if the current route was in that list. E.g.Does the following provide you with sufficient information you require or do you also need the 'request' bit in routeInfo?
If you also require the 'request' bit then you will need to manually do the same thing
dispatchRouterAndPrepareRoute
does.Hope this helps.
Get current Route, even in
middleware
.Here's how you get current route in your middleware in Slim framework 3:
Note that you should use this inside
__invoke()
function in your middleware. Here's the sample usage:$routeInfo shall then contain an object like:
Apparently you can configure Slim to determine the route before going into the middleware with this setting:
I'm not sure what kind of impact this has, but it works for me :)