单个 Route::get() 调用 Laravel 4 中的多个路由

问题描述 投票:0回答:4

在 Laravel 4 中定义路由时,是否可以在同一个路由中定义多个 URI 路径?

目前我执行以下操作:

Route::get('/', 'DashboardController@index');
Route::get('/dashboard', array('as' => 'dashboard', 'uses' => 'v1\DashboardController@index'));

但这违背了我的目的,我想做类似的事情

Route::get('/, /dashboard', array('as' => 'dashboard', 'uses' => 'DashboardController@index'));
php laravel laravel-4
4个回答
26
投票

我相信您需要使用带有正则表达式的可选参数:

Route::get('/{name}', array(
     'as' => 'dashboard', 
     'uses' => 'DashboardController@index')
    )->where('name', '(dashboard)?');

* 假设您想路由到同一控制器,但问题并不完全清楚。

* 当前接受的答案与所有内容匹配,而不仅仅是

/
/dashboard


23
投票

出于好奇,我发现尝试解决这个问题很有趣由@Alex作为评论在@graemec的答案下发布一个可行的解决方案:

Route::get('/{name}', [
    'as' => 'dashboard', 
    'uses' => 'DashboardController@index'
  ]
)->where('name', 'home|dashboard|'); //add as many as possible separated by |

因为

where()
的第二个参数需要正则表达式,所以我们可以将其指定为完全匹配任何由
|
分隔的参数,所以我最初提出将
whereIn()
引入 Laravel 路由的想法是通过此解决方案解决的。

PS:本示例在 Laravel 5.4.30 上测试

希望有人觉得它有用


5
投票

如果我正确理解你的问题,我会说:

使用路由前缀http://laravel.com/docs/routing#route-prefixing

或者 (可选)路由参数http://laravel.com/docs/routing#route-parameters

举个例子:

Route::group(array('prefix' => '/'), function() { Route::get('dashboard', 'DashboardController@index'); });

Route::get('/{dashboard?}', array('as' => 'dashboard', 'uses' => 'DashboardController@index'));

0
投票

Laravel 9 引入了

whereIn
路由约束,它允许您传递一组可接受的路由:

Route::get('/posts/{category}', function () {
    // further logic here
})->whereIn('category', ['movie', 'song', 'painting']);

这在功能上Oluwatobi 使用 where() 的解决方案相同:

Route::get('posts/{category}', function () { // further logic here })->where('category', 'movie|song|painting');
尽管由于使用数组而不是引入整个正则表达式引擎,whereIn 的性能可能稍高一些。

© www.soinside.com 2019 - 2024. All rights reserved.