Issue
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);
Solution
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
Answered By - Pavol Velky
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.