Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional parameter in the middle of a route

Is there any way to add an optional parameter in the middle of a route ?

Example routes:

/things/entities/
/things/1/entities/

I tried this, but it does not work:

get('things/{id?}/entities', 'MyController@doSomething');

I know I can do this...

get('things/entities', 'MyController@doSomething');
get('things/{id}/entities', 'MyController@doSomething');

... but my question is: Can I add an optional parameter in the middle of a route?

like image 355
rap-2-h Avatar asked Jul 23 '15 10:07

rap-2-h


People also ask

Which character lets us create optional route params?

Basically, you can use the ? character to make the parameter optional.

How do you pass optional parameters to a method?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

Can parameters be optional?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.


1 Answers

No. Optional parameters need to go to the end of the route, otherwise Router wouldn't know how to match URLs to routes. What you implemented already is the correct way of doing that:

get('things/entities', 'MyController@doSomething');
get('things/{id}/entities', 'MyController@doSomething');

You could try doing it with one route:

get('things/{id}/entities', 'MyController@doSomething');

and pass * or 0 if you want to fetch entities for all things, but I'd call it a hack.

There are some other hacks that could allow you to use one route for that, but it will increase the complexity of your code and it's really not worth it.

like image 59
jedrzej.kurylo Avatar answered Sep 22 '22 08:09

jedrzej.kurylo