The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

Slim 3.0: Get curent route in middleware

wessel.linden's Avatar

wessel.linden

26 Dec, 2015 11:21 AM

I want to get the name of the current 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?

  1. 1 Posted by kosikredek on 12 Jan, 2016 02:00 PM

    kosikredek's Avatar
            $route = $request->getAttribute('route');
            if (null !== $route) {
                $name = $route->getName();
                var_dump($name);
            }
    

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac