简体   繁体   English

Laravel路由:如何在URI中添加可选参数?

[英]Laravel routing: how to prepend optional parameter in uri?

Realising a API Rest service I'm facing the problem of how/where in the url signature pass the API version. 实现API Rest服务我面临URL签名中如何/何处传递API版本的问题。

By reading around I decided to pass the version like 通过阅读,我决定通过像

http://mydomainservice.tld/api/version/entity ... http://mydomainservice.tld/api/version/entity ...

About treat version as optional and parse the request referring to as latest API version, this would be the intention: 关于将版本视为可选并将解析为最新API版本的请求解析为以下目的:

http://mydomainservice.tld/version/entity ... http://mydomainservice.tld/version/entity ...

The question is not about how to manage/arrange versioning in API rest but more if there's the chance to realise a routing rule to prepend a optional parameter in the URI: 问题不是关于如何在API rest中管理/安排版本控制,而是是否有可能实现路由规则以在URI中添加可选参数,问题更多。

This is 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 http://mydomain.tld/api/subscribers http://mydomain.tld/api/1/subscribers

But I'd like to solve it in a single rule: 但我想用一个规则解决它:

Route::get('{v?}/subscribers', 'APIRequestController@show');

But this second rule won't work by itself if i try to reach out with a request like: 但是,如果我尝试通过以下请求提出请求,则第二条规则本身将无法工作:

http://mydomain.tld/api/subscribers http://mydomain.tld/api/subscribers

This is not possible to do cleanly . 这不可能做到干净利落 Every route parameter requires some kind of value, it can be null when it in the end of URL, but not in a middle of URL. 每个路由参数都需要某种值,当它在URL末尾但不在URL中间时,可以为null。

Despite that, there is super dirty solution: Route::get('{v}subscribers', 'APIRequestController@show')->where('v', '([0-9/]+)?'); 尽管如此,还是有超级肮脏的解决方案: Route::get('{v}subscribers', 'APIRequestController@show')->where('v', '([0-9/]+)?');

Now You can access "yourdomain/api/1/subscribers" as well as "yourdomain/api/subscribers", but make sure You have default value for that v parameter in Your controller. 现在,您可以访问“ yourdomain / api / 1 / subscribers”以及“ yourdomain / api / subscribers”,但是请确保您在控制器中具有该v参数的默认值。 And also You have cut that slash which comes with parameter. 而且,您已经削减了参数附带的斜线。

And finally: don't do this, better write two separate lines and keep code as clean as possibly, than do this kind of magic. 最后:不要做这种事情,比起这种魔术,最好写两行代码并保持代码尽可能整洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM