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.

Leave a Comment