Symfony - multiple paths to the same route within a controller


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:

PHP PHP<?php
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…

  • Mastodon
  • Facebook
  • LinkedIn
  • BlueSky
  • Threads
  • Reddit
  • HackerNews
  • Lobsters
  • WhatsApp
  • Telegram

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?

    Reply

What are your reckons?

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

Allowed HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <p> <pre> <br> <img src="" alt="" title="" srcset="">