Symfony - multiple paths to the same route within a controller

By on   1 comment 150 words, read ~177 times.

I couldn't work out how to use Route Aliasing within my controller. I couldn't find anything in the documentation about it. But, thanks to a StackOverflow comment it is possible.

Suppose you want users to be able to access a page using /users/123 and /people/123 - with both routes displaying the same data?

Normally you'd write something like #[Route('/user/{id}', name: 'show_user')] - as it happens, that first parameter can be an array! Which means you can write:

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class ThingController extends AbstractController

    #[Route(["/user/{id}", "/people/{id}", "/guests/{id}"], name: 'show_user')]
    public function show_user(int $id) {
        // Your logic here

If you need to know which route your user took, call $request->getRequestUri(); to get the string representation, i.e. /user.

Share this post on…

One thought on “Symfony - multiple paths to the same route within a controller

  1. says:

    Oh, TIL. I usually just stack multiple Routes on top and give them all different names.

    Which one does it pick when rendering a path in twig? The first one?


What are your reckons?

All comments are moderated and may not be published immediately. Your email address will not be published.