Laravel 5.4 proper way to store Locale setLocale()

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

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.)

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

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

And remove the auth from the $routeMiddleware array (in your Kernel.php).

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


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.

/**
 * @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>

Tags:

Locale

Laravel