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);
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);
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
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');
}