我正在尝试使用配置 Controller 在 Laravel 7 中更改我的应用程序语言环境:
class ConfigController extends Controller
{
/**
*
* Set the App locale.
*
* @param \SetLocaleRequest $request
* @return mixed
*/
public function set_locale(SetLocaleRequest $request)
{
App::setLocale($request->locale);
return response()->json([
'message' => trans('config.set'),
], 200);
}
}
此代码实际上有效,因为一个简单的 App:getLocale();
返回所提供的语言。无论哪种方式,Lang
门面都继续使用 config/app.php
中提供的默认语言环境,即西类牙语。所以,这段代码:
Lang::get('auth.failed')
正在返回文本:"Estas credenciales no coincident con nuestros registros."
即使当前选择了 en
。知道为什么吗?
最佳答案
动态更改语言环境需要 2 个步骤。我看到你已经完成了第 1 步。第 2 步是在你的 Blade 文件(很可能是基本模板)中做这样的事情:
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
请注意,一旦用户导航到另一个页面,它就会返回配置中设置的语言环境。但是,如果您需要为当前用户维护区域设置,请使用 session 。例如,除了我之前的观点之外,将您的 Controller 方法更改为:
public function set_locale(SetLocaleRequest $request)
{
App::setLocale($request->locale);
Session::put('locale', $request->locale);
return response()->json([
'message' => 'locale.set.success',
], 200);
}
因此,您可以通过以下方式在 Blade 模板中连续访问它:<html lang="{{ str_replace('_', '-', Session::get('locale')) }}">
关于php - Lang facade 未检测到应用程序语言更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61313484/