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. use Slim\App;
  2. use Slim\Exception\NotFoundException;
  3. use Slim\Http\Request;
  4. use Slim\Http\Response;
  5. $app = new App([
  6. 'settings' => [
  7. // Only set this if you need access to route within middleware
  8. 'determineRouteBeforeAppMiddleware' => true
  9. ]
  10. ]);
  11. // routes...
  12. $app->add(function (Request $request, Response $response, callable $next) {
  13. $route = $request->getAttribute('route');
  14. // return NotFound for non existent route
  15. if (empty($route)) {
  16. throw new NotFoundException($request, $response);
  17. }
  18. $name = $route->getName();
  19. $groups = $route->getGroups();
  20. $methods = $route->getMethods();
  21. $arguments = $route->getArguments();
  22. // do something with that information
  23. return $next($request, $response);
  24. });