Laravel 5.4 存储 Locale setLocale() 的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45433877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:48:36  来源:igfitidea点击:

Laravel 5.4 proper way to store Locale setLocale()

laravellocale

提问by Sagynbek Kenzhebaev

I need to know. What is the proper way to store Locale for user. If for each users' request I change the language by

我需要知道。为用户存储区域设置的正确方法是什么。如果对于每个用户的请求,我将语言更改为

    App::setLocale($newLocale);

Would not it change language for my whole project and for other requests as well? I mean when one user changes language it will be used as default for other users.

它不会改变我整个项目和其他请求的语言吗?我的意思是当一个用户更改语言时,它将被其他用户用作默认语言。

Thanks in advance

提前致谢

回答by Dees Oomens

If you set App::setLocale()in for example in your AppServiceProvider.php, it would change for all the users.

App::setLocale()例如,如果您在您的 中设置AppServiceProvider.php,它将为所有用户更改。

You could create a middleware for this. Something like:

您可以为此创建一个中间件。就像是:

<?php

namespace App\Http\Middleware;

use Closure;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        app()->setLocale($request->user()->getLocale());

        return $next($request);
    }
}

(You need to create a getLocale()method on the User model for this to work.)

(您需要getLocale()在 User 模型上创建一个方法才能使其工作。)

And then in your Kernel.phpcreate a middleware group for auth:

然后在您Kernel.php创建一个中间件组auth

'auth' => [
    \Illuminate\Auth\Middleware\Authenticate::class,
    \App\Http\Middleware\SetLocale::class,
],

And remove the authfrom the $routeMiddlewarearray (in your Kernel.php).

auth$routeMiddleware数组(在您的Kernel.php)中删除。

Now on every route that uses the authmiddleware, you will set the Locale of your Laravel application for each user.

现在在使用auth中间件的每条路线上,您将为每个用户设置 Laravel 应用程序的区域设置。

回答by Lyimmi

I solved this problem with a controller, middleware, and with session. This worked for me well, hope it helps you.

我用控制器、中间件和会话解决了这个问题。这对我很有效,希望对你有帮助。

Handle the user request via the controller:

通过控制器处理用户请求:

Simply set the language to the users session.

只需将语言设置为用户会话。

     /**
     * Locale switcher
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function switchLocale(Request $request)
    {
        if (!empty($request->userLocale)) {
             Session::put('locale', $request->userLocale);
        }
        return redirect($request->header("referer"));
    }

Route to switch locale:

切换语言环境的路由:

Route::post('translations/switchLocale}', ['as' => 'translations.switch', 'uses' => 'Translation\TranslationController@switchLocale']);

Middleware to handle the required settings:

处理所需设置的中间件:

In the Middleware check the user's session for the language setting, if its pereset set it.

在中间件中检查用户会话的语言设置,如果它的 pereset 设置了它。

/**
 * @param $request
 * @param Closure $next
 * @param null $guard
 * @return mixed
 */
public function handle(Request $request, Closure $next, $guard = null)
{
   if (Session::has('locale')) {
        App::setLocale(Session::get('locale'));
   }
}

Lastly the switching form:

最后是切换形式:

{!! Form::open(["route" => "translations.switch", "id" => "sideBarLocaleSelectorForm"]) !!}
{!! Form::select("userLocale", $languages, Session::get("locale")) !!}
{!! Form::close() !!}

<script>
    $(document).on("change", "select", function (e) {
        e.preventDefault();
        $(this).closest("form").submit();
    })
</script>

回答by haakym

When someone loads your website it uses the default which is set in the config file.

当有人加载您的网站时,它使用配置文件中设置的默认值。

The default language for your application is stored in the config/app.php configuration file.

应用程序的默认语言存储在 config/app.php 配置文件中。

Using the App::setLocale()method would only change for a specific user which I assume would be set in the session, the config file value would not be altered.

使用该App::setLocale()方法只会更改我认为将在会话中设置的特定用户,不会更改配置文件值。

You may also change the active language at runtime using the setLocale method on the App facade

您还可以在运行时使用 App 外观上的 setLocale 方法更改活动语言

You could see this in action yourself by opening your website in two different browsers (as they would be using two different sessions) then changing the locale in one and seeing the default load in the other.

您可以通过在两个不同的浏览器中打开您的网站(因为它们将使用两个不同的会话),然后在一个浏览器中更改区域设置并在另一个浏览器中查看默认负载,从而亲自看到这一点。

https://laravel.com/docs/5.4/localization#introduction

https://laravel.com/docs/5.4/localization#introduction

回答by Momit Hasan

I was facing the same problem, the locale was changing in session but not in config. So have checked the session's locale in every blade and controller and set the default the language instant from there, here is the code on my blade file

我遇到了同样的问题,语言环境在会话中发生了变化,但在配置中没有发生变化。所以已经检查了每个刀片和控制器中的会话区域设置并从那里设置默认语言即时,这是我的刀片文件中的代码

@php
if(\Session::get('locale') == 'en') 
    \App::setLocale('en');
else                                
    \App::setLocale('bn');

@endphp

@endphp

Hope it will help you

希望它会帮助你

回答by kunal

I have found the best solution. Hope it will help some one in future. if you are setting Locale at Controller function that would not work at all. If you need it be working you can do in routes/web.php. that is very simple.

我找到了最好的解决方案。希望它会在将来对某人有所帮助。如果您在 Controller 功能中设置 Locale,则根本不起作用。如果你需要它工作,你可以在 routes/web.php 中做。这很简单。

Route::get('lang/{lang}', function ($lang)
{
    \App::setLocale($lang);
    return view('front.index');
});

Hope it helps :)

希望能帮助到你 :)