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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵