2

How do I obtain the name of the current route in the controller in Symfony 5? When I try this I get NULL:

$this->Request = Request::createFromGlobals();
$route = $this->Request->attributes->get('_route');

var_dump($route);
  • If you do this, you create a new request instance populated only with PHP superglobals ($_GET, $_POST, etc.). This in done in the public/index.php. During the process of the request, it is populated by the framework with several informations like the route name. You will have to try a way to retrive this request instance depending on your context – Florian Hermann Sep 03 '20 at 13:30

2 Answers2

3

It's not recommended to create request inside your controller. Preferred way of obtaining already created Request is DI and autowiring:

// src/Controller/BlogController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class BlogController extends AbstractController
{
    /**
     * @Route("/blog", name="blog_list")
     */
    public function list(Request $request)
    {
        $routeName = $request->attributes->get('_route');
        $routeParameters = $request->attributes->get('_route_params');

        var_dump($routeName);
    }
}

This request is processed by Symfony HttpKernel and filled with additional information.

More info: https://symfony.com/doc/current/routing.html#getting-the-route-name-and-parameters

How did it get there: https://github.com/symfony/symfony/blob/b2609c4bae69ca383b97cb520da2ed9be1c48449/src/Symfony/Component/Routing/Matcher/UrlMatcher.php#L217

Pavol Velky
  • 770
  • 3
  • 9
2

Found an answer here:

Just add RequestStack as a function parameter and call RequestStack->getCurrentRequest()->get('_route');

use Symfony\Component\HttpFoundation\RequestStack;

public function yourCalledFunction(Utilities $u, RequestStack $requestStack) {

    $route = $requestStack->getCurrentRequest()->get('_route');
}
Agnohendrix
  • 480
  • 1
  • 7
  • 17
  • 2
    Almost but for a controller action you would just use the request object that is injected directly into the controller action. The request stack is used for other non-controller services and would only be injected into the constructor. – Cerad Sep 03 '20 at 13:35
  • i tried this solution on my project and it worked on a controller action with annotated Route. – Agnohendrix Sep 03 '20 at 13:37
  • 2
    Yes it works but it not needed. A controller action will always be injected with the current route as long as you typehint against Request. Using the stack for controllers is just misleading what is obviously a newbie developer. – Cerad Sep 03 '20 at 13:39
  • By the way, if you think the question was answered by an answer in another question then the recommended approach is to just provide a link in the comment section. – Cerad Sep 03 '20 at 21:06