nowilius
nowilius

Reputation: 131

Multilingual website, work with language manipulation?

I use laravel 5.3 framework and have a middleware to check for languages, redirects are correct and localization works, my question is, it is recommended to save selected language in a cookie? So I will be able to redirect the user every time to the selected language? Can it be also good for performance...

At the moment if I call App::getLocale() is get the right language.

I'm generally interested to know is this way correct what I do?

Upvotes: 0

Views: 71

Answers (2)

Ramadhan
Ramadhan

Reputation: 844

For the simple one, you can try this code too..

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $default = config('app.locale');

        // 2. retrieve selected locale if exist (otherwise return the default)
        $locale = Session::get('locale', $default);

        // 3. set the locale
        App::setLocale($locale);

        return $next($request);
    }
}

Upvotes: 0

Asur
Asur

Reputation: 4017

I use this middleware to check/set the language in session for every request:

<?php

namespace App\Http\Middleware;

use App;
use Auth;
use Config;
use Session;
use Closure;

class SetLocale
{
    public function handle($request, Closure $next)
    {
        // If the session doesn't have already a locale
        if (!Session::has('locale')) {
            // Set the logged in user language
            if (Auth::check() && Auth::user()->lang->code) {
                Session::put('locale', Auth::user()->lang->code);
            } else {
                // Else get the http header language and set it
                $requestLanguage = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
                if (App\Lang::where('code', $requestLanguage)->exists()) {
                    Session::put('locale', $requestLanguage);
                } else {
                    // If none of the above worked use the app deafult language
                    Session::put('locale', Config::get('app.locale'));
                }
            }
        }
        // Set the output locale as app locale
        App::setLocale(Session::get('locale'));

        return $next($request);
    }
}

Hope this helps you.

Upvotes: 1

Related Questions