[Symfony] Get the parameters of the current route

Published on 2018-12-11 • Modified on 2018-12-11

The $_route and $_route_params magic variables are available in controllers' actions. We can declare them as function arguments or we can retrieve them from the request's attributes ($request->attributes->get()). I use them regularly to generate breadcrumbs. If you are in a service, you can inject the RequestStack object and get the current request with the getCurrentRequest() function.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

// use Symfony\Component\HttpFoundation\RequestStack;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet9Trait
{
    public function snippet9(Request $request/* string, $_route, array $_route_params, RequestStack $requestStack */): void
    {
        // if you are in a service, inject the RequestStack like below then call
        // $request = $requestStack->getCurrentRequest();

        $route = $request->attributes->get('_route');
        $params = $request->attributes->get('_route_params');

        // in a controller, you can use TypeHint directly the two parameters:
        // public function snippet9(string $_route, array $_route_params)

        echo $route.PHP_EOL;
        print_r($params); // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow  More on the web  Random snippet

  Work with me!