【问题标题】:locale in laravel 5.4 returns to the pervious locale after refreshlaravel 5.4 中的语言环境在刷新后返回之前的语言环境
【发布时间】:2017-03-02 19:17:04
【问题描述】:

我正在学习多语言环境旅馆 laravel 5.4 所以 我创建了两个文件 resources/lang/es/greeting.php 中的第一个

<?php

return [

    'hello' => 'hola',

];

在 resources/lang/en/greeting.php 中排名第二

<?php

return [

    'hello' => 'hola',

];

我在 web.php 中创建了这条路由

Route::get('/{locale}', function ($locale) {
    App::setLocale($locale);
    return view('index');

});

所以当我请求此链接时 (localhost:8000/es) 有用 但是当我刷新页面时,它会返回到默认语言环境,即 en

我希望它保留在新的语言环境中 所以请帮帮我

【问题讨论】:

    标签: php laravel localization locale


    【解决方案1】:

    如果您想为该会话永久设置区域设置,请将路由代码更改为:

    Route::get('/{locale}', function ($locale) {
        App::setLocale($locale);
        Session::put('locale', $locale);
        return view('index');
    });
    

    然后添加一个中间件来检查会话是否有语言环境,如果有,请像这样设置语言环境:

    public function handle($request, Closure $next) {
        if(Session::has('locale')) {
            app()->setLocale(Session::get('locale'));
        }
        return $next($request);
    }
    

    【讨论】:

    • 我按照你说的做了,但我还是有同样的问题
    • 你能把你的整个中间件代码连同 kernel.php 一起发布吗?我假设您注册了中间件并在您的路线中使用了中间件
    • this web.php 中间件('lang');
    • kernel.php protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::类, '绑定' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated: :class, 'lang' => \App\Http\Middleware\Checklang::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ];
    • 中间件 setLocale(Session::get('locale')); } 返回 $next($request); } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2018-08-09
    • 1970-01-01
    • 2018-09-10
    相关资源
    最近更新 更多