在 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'));
我相信您需要使用带有正则表达式的可选参数:
Route::get('/{name}', array(
'as' => 'dashboard',
'uses' => 'DashboardController@index')
)->where('name', '(dashboard)?');
* 假设您想路由到同一控制器,但问题并不完全清楚。
* 当前接受的答案与所有内容匹配,而不仅仅是
/
或 /dashboard
。
出于好奇,我发现尝试解决这个问题很有趣由@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 上测试
希望有人觉得它有用
如果我正确理解你的问题,我会说:
使用路由前缀: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'));
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 的性能可能稍高一些。