首页 > 解决方案 > 具有多个可选值的 Laravel 深度路由

问题描述

我正在寻找解决此问题的最佳方法。

我有一个发布简单搜索的表单,但是有多个可选值。然后控制器将帖子重定向到更易于阅读的 URL。

例如

startdate=2018-01-01
enddate=2018-01-31
department=2,4

这将创建一个 URL

/2018-01-01/2018-01-31/2,4/

但是,如果他们还按员工搜索,则会返回以下内容

employee=9,5,1
/2018-01-01/2018-01-31/2,4/9,5,1/

他们也不能搜索部门而只搜索员工

/2018-01-01/2018-01-31/???/9,5,1/

考虑到这一点,下面显示了完整的 URL 路由计划,您将如何使用嵌套的可选属性?另外,之后您将如何在路线中获得这些值?

Route::get('/{locale}/WIPReport/show/{startdate}/{enddate}/{regions?}/{offices?}/{departments?}/{clients?}/{employees?}', 'WIPReportController@reportdata')
    ->where(['regions' => '[0-9,]+', 'offices' => '[0-9,]+', 'departments' => '[0-9,]+', 'clients' => '[0-9,]+', 'employees' => '[0-9,]+'])

标签: phplaravelrouteslaravel-5.6

解决方案


可以使用多个可选的路由参数,但除非你放/null, /none,/0等,否则你一定会遇到问题。以这个 URL 和 Route 为例:

Route::get("{primary?}/{secondary?}/{tertiary?}", ExampleController@handleColours);

public function handleColours($primary = null, $secondary = null, $tertiary = null){
  // Handle URL
}

"mysite.com/red/blue/green"

在上面,一切正常,因为所有 3 个都已定义。丢弃green也可以,$tertiary默认为null. 接下来,给定这条路线:

"mysite.com/red/green"

如果您打算green成为高等教育,并期望基于此的结果,您会遇到$secondary未在 URL 中定义的问题,因此$secondary会是green和不是null。如果您将 URL 更改为

"mysite.com/red/null/green"
// OR
"mysite.com/red/none/green"
// OR
"mysite.com/red/0/green"

然后事情会按预期运行(给定一些额外的逻辑来翻译字符串或"null"),但 URL 可能会有点混乱。其他选项是使用查询字符串来明确指定参数:"none"null

"mysite.com?primary=red&tertiary=green"

所以有多种方式可以处理;选择最适合你的东西。


推荐阅读