[Symfony] Get the parameters of the current route

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

Because I always forget! 🤔


<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

/**
 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Sf 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Sf <= 4.1)
 * Services are injected in the controller constructor.
 */
trait Snippet9Trait
{
    public function snippet9(Request $request): void
    {
        $route = $request->attributes->get('_route');
        $params = $request->attributes->get('_route_params');

        // Or you can use TypeHint directly in your controller function
        // public function snippet9(string $_route, array $_route_params)

        var_dump($route);
        var_dump($params); // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow