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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?