duanfen1312 2018-03-02 01:45
浏览 717
已采纳

如何在Laravel中设置动态路由前缀?

I need to create an app with multiple locales. And each route is prefixed with the locale. For example, xxx.com/en/home, xxx.com/fr/home.

The thing is, I need to dynamically bind the locale string to route prefix. Since users can change locale, the locale string is stored in session. And I need reference to the session on web.php. Session object can't be used in the globle scope on web.php, meaning session('key') won't get you anything (null) in the outermost scope except in route functions because Laravel parses web.php before instantiating any session object, I think. Therefore I face a conundrum in that I can't reference session in the outermost scope on web.php while I need session to create dynamic prefix. How can I solve this?

  • 写回答

3条回答 默认 最新

  • dongsu3664 2018-03-02 05:32
    关注

    I recently prefixed my routes with locale and I found it pretty easy to implement using mcamara's Laravel Localization package. After setting up the package installation, I just had to add a route group for all the URLs I wanted with locale prefix.

    Route::group([
        'prefix' => LaravelLocalization::setLocale(),
        'middleware' => ['localeSessionRedirect', 'localizationRedirect']
    ], function()
    {
       Route::get('/contact', 'HomeController@contact_page');
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘