如何配置Laravel Router一些路由规则在不同的路径上工作?

时间:2015-10-20 09:04:25

标签: laravel laravel-routing

我在A.com部署了我的Laravel 5项目,我也希望将其放在B.com/a下。出于某种原因,我应该在路由器中处理/a路径。

所以在路由器中写道: Route::get('post','PostController@index'); Route::get('a/post','PostController@index'); 这不是一个好方法,因为存在冗余,特别是有很多其他路由规则。

在doc中,只有{xx}?来处理可选参数,但在我的项目中,它不是param而是静态字符串。

有没有更好的方法来组合两条线?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

RealRoutes.php:

Route::get('post','PostController@index');
// ... include all of your other routes here

routes.php文件:

include('RealRoutes.php');
Route::group(['prefix' => 'a/'], function () {
    include('RealRoutes.php');
});

使用lambda函数或类似功能可能有更好的方法来解决这个问题,但上述内容应该可以作为一种快速解决方案。

答案 1 :(得分:1)

我在foreach循环中使用路由前缀。这样,您就可以快速轻松地管理路线上的前缀,同时将它们全部保存在一个位置。

foreach([null, 'a'] as $prefix) {
    Route::group(['prefix' => $prefix], function () {
        // Your routes here
    });
}

未加前缀的路由将优先,因为在这种情况下将首先生成其路由。如果需要,你可以轻松地交换数组。

如果您真的想在单个路线定义中进行,可以使用正则表达式来匹配路线。

Route::get('{route}', function () {
    dd('Browsing ' . app('request')->path());

})->where('route', '(a/)?post');

但它显然不是很干净/可读,所以可能不推荐。