【问题标题】:Adding multiple prefix in a single route group in Laravel在 Laravel 的单个路由组中添加多个前缀
【发布时间】:2016-10-26 06:04:12
【问题描述】:

有没有办法在 Laravel 的单个路由组中添加多个前缀?

Route::group(['prefix' => 'prefix'], function (){
   Route::get('hello', 'HelloController@sayHello');
});

我尝试过使用管道添加-

Route::group(['prefix' => 'prefix1|prefix2'], function (){
   Route::get('hello', 'HelloController@sayHello');
});

也尝试使用数组-

Route::group(['prefix' => ['prefix1', 'prefix2']], function (){
   Route::get('hello', 'HelloController@sayHello');
});

但没有运气。真的有办法吗?

【问题讨论】:

    标签: laravel-5 routes


    【解决方案1】:

    您是否尝试过像这样调用where 方法:

    Route::group(['prefix' => '{prefix}'], function (){
        Route::get('hello', 'HelloController@sayHello')->where('prefix', 'prefix1|prefix2');
    });
    

    更新

    如果您想以更有效的方式进行操作,可以尝试一下,例如:

    Route::group(['prefix' => '{prefix}'], function (){
        $routes = [];
        $routes[] = Route::get('hello', 'HelloController@sayHello');
        $routes[] = Route::get('other', 'HelloController@other');
        foreach($routes as $route) {
            $route->where('prefix', 'prefix1|prefix2');
        }
    });
    

    但这只是我的第一个想法。也许你可以找到另一个更好的。

    【讨论】:

    • 它似乎工作。但是,如果我需要在这个路由组中将 10-20 条路由分组,那么将 where 子句添加到所有这些路由将是低效的。那么,是不是更容易做到呢?
    • 可能您需要添加一些辅助函数或其他东西以使其更干净。我会在我的条目中向你推荐一个。
    • 好的。非常感谢。 :)
    • 仅供参考 - 如果您使用这种方法,请记住,您的控制器在此路由下的所有操作都将接收前缀变量作为第一个参数,因为它将被视为路由参数。
    【解决方案2】:

    让我再举一个例子,只是为了处理偶尔的情况:

    // The Route Name point to multiple prefixes 
    // according to locale using the same Controller
    
    $contactRoutes = function () {
        Route::get('', ['uses' => 'ContactController@index', 'as' => 'contact');
        Route::post('', ['uses' => 'ContactController@send', 'as' => 'contact.send');
    };
    switch (env('APP_LOCALE')) {
        case 'pt': 
            Route::group(['prefix' => 'contato'], $contactRoutes);
            break;
        case 'es':
            Route::group(['prefix' => 'contacto'], $contactRoutes);
            break;
        default: //en
            Route::group(['prefix' => 'contact'], $contactRoutes);
            break;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2021-01-05
      • 1970-01-01
      • 2011-03-22
      • 2017-01-18
      相关资源
      最近更新 更多