Retrieving Current Route

If you ever need to get access to the current route within your application all you have to do is call the request class’ getAttribute method with an argument of 'route' and it will return the current route, which is an instance of the Slim\Route class.

From there you can get the route’s name by using getName() or get the methods supported by this route via getMethods(), etc.

Note: If you need to access the route from within your app middleware you must set 'determineRouteBeforeAppMiddleware' to true in your configuration otherwise getAttribute('route') will return null. Also getAttribute('route') will return null on non existent routes.

Example:

  1. <?php
  2. use Slim\Factory\AppFactory;
  3. use Slim\Routing\RouteContext;
  4. require __DIR__ . '/../vendor/autoload.php';
  5. $app = AppFactory::create();
  6. // Via this middleware you could access the route and routing results from the resolved route
  7. $app->add(function (Request $request, RequestHandler $handler) {
  8. $routeContext = RouteContext::fromRequest($request);
  9. $route = $routeContext->getRoute();
  10. // return NotFound for non existent route
  11. if (empty($route)) {
  12. throw new NotFoundException($request, $response);
  13. }
  14. $name = $route->getName();
  15. $groups = $route->getGroups();
  16. $methods = $route->getMethods();
  17. $arguments = $route->getArguments();
  18. // ... do something with the data ...
  19. return $handler->handle($request);
  20. });
  21. // The RoutingMiddleware should be added after our CORS middleware so routing is performed first
  22. $app->addRoutingMiddleware();
  23. // ...
  24. $app->run();