gpt4 book ai didi

laravel-4 - Laravel 路由 url 参数顺序可变

转载 作者:行者123 更新时间:2023-12-02 09:47:30 29 4
gpt4 key购买 nike

我正在考虑路由到 GET URL 的 Controller ,其参数的数量或它们在 URL 中出现的顺序可能会有所不同。可能有很多这样的组合,我想为所有这些 URL 调用相同的 Controller 操作

我的网址示例:

  1. Route::get('route1/id/{id}', 'Controller1@controllerAction1');
  2. Route::get('route1/id/{id}/name/{name}', 'Controller1@controllerAction1');
  3. Route::get('route1/name/{name}', 'Controller1@controllerAction1');
  4. Route::get('route1/id/{id}/name/{name}/orderby/{orderby}', 'Controller1@controllerAction1');
  5. Route::get('route1/id/{id}/orderby/{orderby}', 'Controller1@controllerAction1');

此外,在 Controller 操作中,我最终希望将此查询字符串分解为数组。对于上面提到的第二个示例,我希望将查询字符串 id/{id}/name/{name} 转换为数组 ('id' => {id}, 'name ' => {name})

要为 URL 的所有不同变体调用相同的 Controller 操作,我的routes.php 中有以下代码:

Route::get('route1{all}', 'Controller1@controllerAction1')->where('all', '.*')

这似乎为上述不同类型的 URL 调用了 Controller1 的“controllerAction1”。

在函数controllerAction1中,我正在做

$route_input = Route::input('all'); 
var_dump($route_input);
which prints "/id/1/name/xyz" when I hit http://example.com/laravel/public/route1/id/1/name/xyz

我想知道是否:

  1. Doing Route::get('route1{all}', 'Controller1@controllerAction1')->where('all', '.*') is the right method to invoke same action for variable combination of get parameters?
  2. Does Laravel offer any function to convert "/id/1/name/xyz" to array('id' => 1, 'name' => 'xyz') or I need to write custom function?
  3. Is there a better way to achieve my requirements?

最佳答案

  1. 我相信不会。另外,这样您将无法理解正在传递哪些值。

  2. 即使有一个,我认为您实际上也不需要传递数组。恕我直言,我更喜欢将这些项目分开,然后通过 Controller 操纵它们。这只是我个人的建议,但是如果您需要一组数据,为什么不使用 POST 方法呢? (唯一正确的答案是您希望用户能够保存链接:P)

  3. 关于您的请求的复杂部分是您希望将所有内容保留在同一 Controller 操作下,这会弄乱路由。我会尝试这个(在你的 routes.php 中):

    Route::pattern('id', '[0-9]+');    Route::pattern('name', '[a-Z]+');    Route::get('route1/{id}/{name?}/{orderby?}', 'Controller1@controllerAction1');    Route::get('route1/{name}/{orderby?}', 'Controller1@controllerAction1');

这样:

  • 您可以拥有一条仅包含 ID 的路线,其中 NAME 和 ORDERBY 是可选的

  • 如果没有传递ID,则可以有一条只有NAME的路由,其中​​ORDERBY是可选的

请注意这与您的 URL 有何不同:按照您编写的方式放置路由要复杂得多 id/{id}/name/{name} ,比我建议的方式{id}/{name} 。如果您完全需要它们,为什么不调用从 GET 函数传递变量的链接,如下所示? <a href="http://www.yoursite.com/route1?id=xxxx&name=yyyy&orderBy=zzzz" rel="noreferrer noopener nofollow">http://www.yoursite.com/route1?id=xxxx&name=yyyy&orderBy=zzzz</a>

关于laravel-4 - Laravel 路由 url 参数顺序可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22307478/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com