如何在Laravel中设置动态路由前缀? [英] How to set dynamic route prefix in Laravel?

查看:540
本文介绍了如何在Laravel中设置动态路由前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个具有多个语言环境的应用程序.并且每个路由都以区域设置为前缀.例如,xxx.com/en/homexxx.com/fr/home.

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.

问题是,我需要将语言环境字符串动态绑定到路由前缀.由于用户可以更改区域设置,因此区域设置字符串存储在会话中.我需要参考web.php上的会话.会话对象不能在web.php的全局范围内使用,这意味着session('key')在最外面的范围内不会给您任何东西(null),除了路由功能外,因为Laravel在实例化任何会话之前会解析web.php我认为是对象.因此,我面临一个难题,因为当我需要创建动态前缀的会话时,无法在web.php的最外部作用域中引用会话.我该如何解决?

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?

推荐答案

我最近在我的路线上添加了语言区域前缀,并且发现使用 mcamara的Laravel本地化软件包.设置完软件包安装后,我只需要为我想要的所有带有区域设置前缀的URL添加一个路由组即可.

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');
});

这篇关于如何在Laravel中设置动态路由前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆