kevin_marcus
kevin_marcus

Reputation: 277

How to retain Laravel 5 selected local language?

For example, I log in and selected en as my language and then I select zh (chinese) and then log out. Is there any way to retain the localization after you log-out the app?

this is the way I implement locale.

web.php:

Route::post('change-locale', 'LocaleController@changeLocale')->name('change.locale');

LocaleController:

class LocaleController extends Controller
{
    /**
     * @param Request $request
     */
    public function changeLocale(Request $request) {

        $this->validate($request, ['locale' => 'required|in:' . implode(',', config('app.available_locales'))]);

        Session::put('locale', $request->input('locale'));

        return redirect()->back();
    }

}

Logout:

public function logout(Request $request)
    {
        $this->guard()->logout();
        $locale =  session('locale');
        $locale = Session::put('locale', $locale);
        Session::flush();
        //$request->session()->invalidate();
        //$request->session()->put('locale',$locale);
        return redirect('/login');
    }

Locale Setting:

 public function handle($request, Closure $next)
    {
        if (Session::has('locale')) {
            $locale = Session::get('locale', Config::get('app.locale'));
        } else {
            $locale = substr($request->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);

            if (!in_array($locale, Config::get('app.available_locales'))) {
                $locale = 'en';
            }
        }        
        App::setLocale($locale);

        return $next($request);
    }

Upvotes: 3

Views: 1898

Answers (2)

mart
mart

Reputation: 354

I do it this way in Laravel 6:

Add to /app/Http/Controllers/Auth/LoginController.php this two functions:

public function logout(Request $request)
{
    $locale =  Session::get('locale');
    $this->guard()->logout();

    $request->session()->invalidate();

    return $this->loggedOut($request, $locale) ?: redirect('/');
}

protected function loggedOut(Request $request, $locale)
{
    Session::put('locale',$locale);
}

and this uses:

use Illuminate\Http\Request;
use Session;

Upvotes: 2

Ravindra Bhanderi
Ravindra Bhanderi

Reputation: 2936

if you into session then that value you can get through

$locale =  Session::get('locale');
Session::flush();
Session::set('locale',$locale);

what i do, i use session global helper for get session value you can get any where this value

Upvotes: 3

Related Questions