Home » Php » php – Symfony2 Accessing route variables

php – Symfony2 Accessing route variables

Posted by: admin July 12, 2020 Leave a comment

Questions:

I know I can access current route name by $request->get('_route');.

If my route is defined this way:

/*
 * @Route("/get_by_category/{id}", defaults={"id" = 0}, name="get_products_by_category")
 */

How can I retrieve the id variable from within service?

How to&Answers:

You can get all route related parameters from the Request

$routeParams = $request->attributes->get('_route_params');
$id = $routeParams['id'];

Answer:

$request->attributes->get('id') does the trick.

Answer:

You can do

/*
* @Route("/get_by_category/{id}", defaults={"id" = 0}, name="get_products_by_category")
*/
public function getProductsAction($id)
{
}

The $id variable will be available within the controller.