2 Methods to Get Route Parameters in Symfony 7

2 Methods to Get Route Parameters in Symfony 7

In Symfony application, routes can be defined with dynamic URL which contains parameters. Parameters are wrapped in curly brackets {param_name} and they must have a unique name.

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

Method 1 - Request object

The Request object contains route configuration which stored in the public attributes property. It is an instance of ParameterBag. The get method can be used to retrieve route parameters from attributes property by _route_params 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('/{page}')]
    public function index(Request $request): Response
    {
        $routeParams = $request->attributes->get('_route_params');

        return new Response($routeParams['page']); // If http://localhost/5 then output: 5
    }
}

Method 2 – $_route_params parameter

We can use $_route_params parameter in a controller to get route parameters.

src/Controller/TestController.php

<?php

namespace App\Controller;

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

class TestController
{
    #[Route('/{page}')]
    public function index(array $_route_params): Response
    {
        return new Response($_route_params['page']); // If http://localhost/5 then output: 5
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.