【问题标题】:Defining Route in Laravel在 Laravel 中定义路由
【发布时间】:2019-11-18 16:06:30
【问题描述】:

我在这里遇到了一个“奇怪”的情况。我需要以同样的方式处理以下路线:

domain.com/common/p1
domain.com/common/p1/p2
domain.com/common/p1/p2/p3

这意味着,基本上,路线应该是这样的:

Route::get('common/{path}', function ($path) {
    //should execute for all paths after common
});

有没有我可以使用的正则表达式?

【问题讨论】:

  • 你想做什么?

标签: php laravel routes


【解决方案1】:

查看更多:https://laravel.com/docs/5.8/routing

你可以使用:

Route::get('common/{path}', function ($path) {
    //should execute for all paths after common
})->where('path', '(.*)');

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    Laravel 路由组件允许除 / 之外的所有字符。您必须使用 where 条件正则表达式明确允许 / 成为占位符的一部分:

    Route::get('common/{path}', function ($path) {
        //should execute for all paths after common
    })->where('path', '.*');
    

    【讨论】:

      【解决方案3】:

      我认为您可以使用以下代码实现此目的。

      Route::any('/common/{args?}', function($args){
         $args = explode('/', $args);
         // do your code by passing argument to controller
      })->where('args', '(.*)');
      

      【讨论】:

        【解决方案4】:

        是的,你可以..

        Route::get('common/{path}', function ($path) {
        //should execute for all paths after common
        })->where('path', 'YOUR REGEX GOES HERE');
        

        【讨论】:

          【解决方案5】:

          您正在寻找optional parameters

          您的代码如下所示:

          Route::get('common/{path1?}/{path2?}/{path3?}', function ($path1=null, $path2=null, $path3=null) {
              //
          });
          

          对于无限参数使用:

          Route::get('common/{path?}', 'Controller@Method')->where('path', '.*');
          

          这将在您的控制器方法中生成一个路径数组。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-08-16
            • 2018-10-04
            • 2018-06-30
            • 2018-12-16
            • 2017-09-08
            • 1970-01-01
            相关资源
            最近更新 更多