php - Laravel routing: how to prepend optional parameter in uri? -
realising api rest service i'm facing problem of how/where in url signature pass api version.
by reading around decided pass version like
http://mydomainservice.tld/api/version/entity...
about treat version optional , parse request referring latest api version, intention:
http://mydomainservice.tld/version/entity...
the question not how manage/arrange versioning in api rest more if there's chance realise routing rule prepend optional parameter in uri:
this working:
route::group(['prefix' => 'api/'], function(){ route::get('{v}/subscribers', 'apirequestcontroller@show'); route::get('subscribers', 'apirequestcontroller@show); });
for both calls like:
http://mydomain.tld/api/subscribers http://mydomain.tld/api/1/subscribers
but i'd solve in single rule:
route::get('{v?}/subscribers', 'apirequestcontroller@show');
but second rule won't work if try reach out request like:
this not possible cleanly. every route parameter requires kind of value, can null when in end of url, not in middle of url.
despite that, there super dirty solution: route::get('{v}subscribers', 'apirequestcontroller@show')->where('v', '([0-9/]+)?');
now can access "yourdomain/api/1/subscribers" "yourdomain/api/subscribers", make sure have default value v
parameter in controller. , have cut slash comes parameter.
and finally: don't this, better write 2 separate lines , keep code clean possibly, kind of magic.
Comments
Post a Comment