2 Methods to Get Route Name in Symfony 7

2 Methods to Get Route Name in Symfony 7

In Symfony application, each route is identified by the name, which can be used for generating URLs. If route name is not explicitly set, the name will be generated automatically.

This tutorial provides 2 methods how to get route name in Symfony 7 application.

Method 1 - Request object

The Request object has route configuration which stored in the public attributes property. It is an instance of ParameterBag. We can use the get method to retrieve route name from attributes property by _route key.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    #[Route('/', name: 'test_index')]
    public function index(Request $request): Response
    {
        $routeName = $request->attributes->get('_route');

        return new Response($routeName); // Output: test_index
    }
}

Method 2 - $_route parameter

If you need to get route name in a controller, you can use $_route parameter.

src/Controller/TestController.php

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class TestController
{
    #[Route('/', name: 'test_index')]
    public function index(string $_route): Response
    {
        return new Response($_route); // Output: test_index
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.