Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony routing: match anything after first node

I'd like to do something like this:

/**
 * @Route("^/secured") <-- this would not work, just an example
 */
public function securedAction(){
  //return secured JS frontend 
}

and have symfony match any routes (.com/secured/something; .com/secured/anything/else) to this one action without defining all the routes manually.

Does symfony support this? I can't think of the terms to search for this.

How can I match and route to this controller action without defining all routes manually, based off the first node (/secured)?

like image 248
Theodore Enderby Avatar asked Feb 01 '26 01:02

Theodore Enderby


1 Answers

/**
 * @Route("/secured/{anything}", name="_secured", defaults={"anything" = null}, requirements={"anything"=".+"})
 */

public function securedAction($anything){
    //return secured JS frontend 
}

name - just name of the route.

defaults - here you can set default value of the parameter, if you not provide parameter in the url: /secured/

requirements - requirements for parameter(s), in this case anything can contain forward slash: http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html , but you must handle it in your controller action yourself:

for example if you provide url: /secured/anything/another_thing/one_more_thing

you can get all parameters by explode('/', $anything);

and the results will be:

array:3 [
  0 => "anything"
  1 => "another_thing"
  2 => "one_more_thing" ]

Just everything after /secured/ will be one parameter $anything.

like image 57
malcolm Avatar answered Feb 02 '26 13:02

malcolm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!