【问题标题】:Laravel routing url with variable order of parameters具有可变参数顺序的 Laravel 路由 url
【发布时间】:2014-04-13 23:42:26
【问题描述】:

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

我的 URL 的外观示例:

  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 变体调用相同的控制器操作,我的 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. 正在做 Route::get('route1{all}', 'Controller1@controllerAction1')->where('all', '.*') 是对的 为 get 的变量组合调用相同操作的方法 参数?
  2. Laravel 是否提供任何函数来转换 "/id/1/name/xyz" 到数组('id' => 1, 'name' => 'xyz') 或者我需要 写自定义函数?
  3. 有没有更好的方法来实现我的 要求?

【问题讨论】:

    标签: laravel-4


    【解决方案1】:

    要将路由参数从一组单独的参数转换为包含 Laravel 5 中所有参数的数组,您可以从 Controller 中调用它:

    $routeParameters = $this->getRouter()->getCurrentRoute()->parameters()

    对于路由定义 Route::get('route1/id/{id}/name/{name}', 'Controller1@controllerAction1'); 如果用户点击以下路线:/route1/id/2/name/john

    $routeParameters 等于 array(id => 2, name => 'john')

    【讨论】:

      【解决方案2】:
      1. 我不相信。另外,这样您将无法了解正在传递哪些值。

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

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

      路线::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}/{name} 相比,在您编写路由 id/{id}/name/{name} 时放置路由要复杂得多。如果您完全按照自己的方式需要它们,为什么不调用从 GET 函数传递变量的链接,如下所示? @987654321@

      【讨论】:

      • 感谢您的回复。我喜欢你的建议。我会尝试yoursite.com/route1?id=xxxx&name=yyyy&orderBy=zzzz 格式。
      • @user3402821 不客气 :) 你能接受答案吗?否则其他人会浪费时间回答
      • 我将按照 yoursite.com/route1?id=xxxx&name=yyyy&orderBy=zzzz 格式。谢谢回答
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-04
      • 2020-05-10
      • 2018-08-31
      • 1970-01-01
      • 2018-12-23
      • 2020-02-09
      • 2015-10-30
      相关资源
      最近更新 更多