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?
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.
Having the optional parameter in the middle of the route definition like that, will only work when the parameter is present. Consider the following:
- when accessing the path
things/1/entities
, the id
parameter will correctly get the value of 1
.
- when accessing the path
things/entities
, because Laravel uses regular expressions that match from left to right, the entities
part of the path will be considered to be the value of the id
parameter (so in this case $id = 'entitites';
). This means that the router will not actually be able to match the full route, because the id
was matched and it now expects to have a trailing /entities
string as well (so the route that would match would need to be things/entities/entities
, which is of course not what we're after).
So you'll have to go with the separate route definition approach.