Symfony2 Route get parameter only if integer
Asked Answered
A

2

6

I got defined routes in routing.yml file

one route is:

Profile_user_profile:
    path:    /profile/{id}
    defaults: { _controller: ProfileBundle:Users:profile }
    methods: [get]

and second is:

Profile_accept_connection_proposal:
    path:    /profile/acceptProposal
    defaults: { _controller:ProfileBundle:Users:acceptConnectionProposal }
    methods: [put]

First route without methods: [get] listen also and [put] request and catch second url before it get to route definition. Is there way to define checking for parameter only if url is numeric.

Armindaarming answered 21/7, 2016 at 19:19 Comment(0)
A
8

Just add the requirements parameter to accept only digits for a determined route like this:

Profile_user_profile:
    path:    /profile/{id}
    defaults: { _controller: ProfileBundle:Users:profile }
    methods: [get]
    requirements: <--- ADDED PARAMETER
        id: \d+

For more infos read the Symfony book about Routing. There you can find more advanced example on how to use route parameters.

Architectural answered 21/7, 2016 at 19:37 Comment(0)
V
8

You can now do this with Annotations in your controller like so:

class UserController extends AbstractController
{
    /**
     * @Route("/profile/{id}", name="user_profile", requirements={"id"="\d+"})
     */
    public function profile($id)
    {
        // ...
    }
}

More info on Symfony's docs Specifically defining routing requirements

Valtin answered 26/9, 2018 at 12:52 Comment(1)
For Symfony 6, do that : #[Route('/profile/{id}', name: 'user_profile', requirements: ['id' => '\d+'])]Nostradamus

© 2022 - 2025 — McMap. All rights reserved.