【问题标题】:Optional routes with dashes带有破折号的可选路线
【发布时间】:2015-01-05 09:09:47
【问题描述】:

我想像这样创建 3 条不同的路线:

Route::get('schedule',['as'=>'schedule.view','uses'=>'ScheduleController@view']);
Route::get('schedule/{year}-{month}',['as'=>'schedule.view','uses'=>'ScheduleController@view'])
    ->where('year','\d{4}')
    ->where('month','0[1-9]|1[0-2]');

Route::get('schedule/{year}-{month}-{day}',['as'=>'schedule.view','uses'=>'ScheduleController@view'])
    ->where('year','\d{4}')
    ->where('month','0[1-9]|1[0-2]')
    ->where('day','0[1-9]|[12][0-9]|3[01]');

即,您可以提供以下之一:

  • 没有年/月/日
  • 年月
  • 年、月、日

当我使用route('schedule.view', ['2015','01','01]) 链接到它们时,路由按原样工作,但如果我省略参数,它会尝试链接到/schedule/{year}-{month}-{day}(实际上有大括号!)。

有没有办法让 laravel 表现得更聪明,还是我必须给我的每条路线一个不同的名字?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    这绝对不可能,因为route() 从一个按名称索引的数组中读取它们。 每个名称一条路线。所以看起来只有最后一个路由会在该数组中,而其他路由会被覆盖。

    returns the route 的功能除了:

    return isset($this->nameList[$name]) ? $this->nameList[$name] : null;
    

    所以似乎要换个名字。

    【讨论】:

    • 人力资源部。我认为如果我重新定义路由名称,它应该会出错。我想也许它可能很聪明,并考虑 args 的数量。或者也许我可以以某种方式重写路线,例如schedule/{{year}-{month}}?{-{day}}?。那好吧。这没什么大不了的,谢谢!
    • 看起来当多个路由定义为同名时抛出异常是有意义的。也许还有其他功能实际上适用于每个名称 idk 的多个路由。使用可选参数定义一条路线可能是另一种解决方案。
    猜你喜欢
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2012-07-03
    • 2012-10-01
    相关资源
    最近更新 更多