Lang facade 未检测到应用程序语言更改

Lang facade not detecting app lang change

我正在尝试使用配置控制器在 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(); returns 语言。无论哪种方式,Lang 门面都继续使用 config/app.php 提供的默认语言环境,即西班牙语。所以,这段代码:

Lang::get('auth.failed')

正在返回文本:"Estas credenciales no coinciden con nuestros registros.",即使当前选择了 en。知道为什么吗?

动态更改语言环境需要 2 个步骤。我看到你已经完成了第 1 步。第 2 步是在你的 blade 文件(很可能是基本模板)中做这样的事情:

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

请注意,一旦用户导航到另一个页面,它就会返回配置中设置的语言环境。但是,如果您需要为当前用户维护区域设置,请使用 session。例如,除了我之前的观点之外,将您的控制器方法更改为:

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