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
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
.
Dominik says:
Oh, TIL. I usually just stack multiple
Route
s on top and give them all different names.Which one does it pick when rendering a path in twig? The first one?
More comments on Mastodon.