我在我的 Laravel 5.2 应用程序中使用了 2 种语言。我目前正在实现一个简单的密码提醒页面,由于我不知道的原因,我在以正确的语言发送新密码电子邮件时遇到了问题。
假设我看到的是德语页面。在页面 View 中,我使用 Facades 回显 2 个值:
echo App::getLocale();
echo Session::get('locale');
该页面以德语提供,因此两个 值与de
相呼应。
现在,我在表单中输入电子邮件地址并提交。输入到达 Controller 方法并调用库向用户发送新密码:
public function resetPassword() {
// Validate the input, retrieve the user...
Mailer::sendNewPasswordEmail($user); // Call to the library sending emails
}
最后,在库中,我 var_dump 了相同的 2 个值,如下所示:
public static function sendNewPasswordEmail($user) {
var_dump(App::getLocale());
var_dump(Session::get('locale'));
die;
}
在这种情况下,Session::get('locale')
仍然等于 de
,但 App::getLocale()
显示 zh
.
为什么,为什么,为什么?
在我的电子邮件模板中,我使用了 Blade 的 @lang()
指令。据我所知,该指令检查应用程序区域设置以确定要提供的翻译。就我而言,电子邮件始终以英语发送,我不知道为什么 App::getLocale()
在 View 中和我发出的下一个 POST 请求期间返回不同的值。
顺便说一下,这不是第一次发生了。有时, View 似乎比 Controller 、模型或库更“了解”实际应用程序的区域设置。令人困惑。
想法?
最佳答案
Laravel 5.2 App_Locale 不是持久的。我发现使语言环境正常工作的唯一方法是创建一个像这样调用 App::setLocale() 的中间件:
<?php namespace App\Http\Middleware;
use Closure;
use Session;
use App;
use Config;
class Locale {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
App::setLocale(Session::get('locale'));
return $next($request);
}
}
在 Kernel.php 上注册您的中间件
protected $middleware = [
.
.
.
'App\Http\Middleware\Locale'
];
关于php - 为什么 Laravel 的 App::getLocale() 方法不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38229369/