mcamara/laravel-localization 命名路由本地化
mcamara/laravel-localization named routes localization
我根据文档在 laravel 5.6
中设置了 mcamara/laravel-localization 1.3 库,在 users
table 中我创建了 lang
列,每次用户切换语言(这允许我以正确的语言发送 "background" 循环电子邮件或在用户登录后设置正确的语言)。我在 LaravelLocalization::setLocale()
组中的 web.php
中设置了所有路线(如文档所述)。
我想在我的控制器中使用命名路由,例如用于在用户登录后重定向到正确的页面(用户来自 EN 登录页面,但他的 lang='pl'
)。在我的 LoginController@redirectTo()
中,我只使用:
App::setLocale(Auth::user()->lang);
$url = route('dashboard.index');
return $url;
// current result $url = 'http://ebnavi.localhost/en/panel/raporty'
// desired result $url = 'http://ebnavi.localhost/pl/panel/raporty'
没用。我没有在文档中找到关于此的直接说明。
那么怎么做呢?
几个小时后,我终于在互联网上找到了 this solution:
$url = LaravelLocalization::getLocalizedURL($locale, route($routeName));
并创建以下helper function来实现这个任务
function localRoute($routeName, $locale = null)
{
if (!$locale && Auth::user()) $locale = Auth::user()->lang;
return $locale ? LaravelLocalization::getLocalizedURL($locale, route($routeName)) : route($routeName);
}
在我们的控制器中,我们可以这样使用它:
$url = localRoute('dashboard.index');
但是可能存在一些更好的方法吗?
我解决了这个问题
授权成功,需要从数据库发送用户locale
LoginController\authenticated
\LaravelLocalization::setLocale(\Auth::user()->language);
在页面上 HTML 指定活动语言环境
<html lang="{{ \LaravelLocalization::setLocale(\Auth::user()->language) }}">
我根据文档在 laravel 5.6
中设置了 mcamara/laravel-localization 1.3 库,在 users
table 中我创建了 lang
列,每次用户切换语言(这允许我以正确的语言发送 "background" 循环电子邮件或在用户登录后设置正确的语言)。我在 LaravelLocalization::setLocale()
组中的 web.php
中设置了所有路线(如文档所述)。
我想在我的控制器中使用命名路由,例如用于在用户登录后重定向到正确的页面(用户来自 EN 登录页面,但他的 lang='pl'
)。在我的 LoginController@redirectTo()
中,我只使用:
App::setLocale(Auth::user()->lang);
$url = route('dashboard.index');
return $url;
// current result $url = 'http://ebnavi.localhost/en/panel/raporty'
// desired result $url = 'http://ebnavi.localhost/pl/panel/raporty'
没用。我没有在文档中找到关于此的直接说明。
那么怎么做呢?
几个小时后,我终于在互联网上找到了 this solution:
$url = LaravelLocalization::getLocalizedURL($locale, route($routeName));
并创建以下helper function来实现这个任务
function localRoute($routeName, $locale = null)
{
if (!$locale && Auth::user()) $locale = Auth::user()->lang;
return $locale ? LaravelLocalization::getLocalizedURL($locale, route($routeName)) : route($routeName);
}
在我们的控制器中,我们可以这样使用它:
$url = localRoute('dashboard.index');
但是可能存在一些更好的方法吗?
我解决了这个问题
授权成功,需要从数据库发送用户locale
LoginController\authenticated
\LaravelLocalization::setLocale(\Auth::user()->language);
在页面上 HTML 指定活动语言环境
<html lang="{{ \LaravelLocalization::setLocale(\Auth::user()->language) }}">