Norbertho's avatar

Store users selected language option

Hi, I am creating an app.and currently I store the user selected language option in session and it works perfectly for example if user selects English language then I store the 'en' in session with the following controller:

    public function index($locale){
        App::setlocale($locale);
        session()->put('locale', $locale);
        return redirect()->back();
    }

and I do the following in a middleware:

public function handle($request, Closure $next) {
        if (session()->has('locale')) {
            App::setlocale(session()->get('locale'));
        }else{
            App::setlocale('hu');
            session()->put('locale', 'hu');
        }
        return $next($request);
    }

It works fine user can navigate trough the app back and forward and the selected language is stay as users selected. I can log in into app and the selected language option is stay as selected and stored in session. However when the user logout from the app and redirected to the welcome page then the session is reset and the selected language cleared and the default language is set. Is there any way to prevent the logout function to clear the selected language optino?

0 likes
4 replies
aurawindsurfing's avatar

@norbertho This is how session should work. It is not a bug, it is feature.

Think about it, one user logs out then there should be no session associated with him or his browser. He is a guest and should receive default guest settings.

Norbertho's avatar

@aurawindsurfing I know it is a feature and not a bug. I dont complain about it my question is is there any way to keep only that variable in the session ? If i save it in cookie would be the same result? Or is there a way to modify the logout function that just before it do the return redirect to the welcome page i set the language variable in the session?

Snapey's avatar

You have to instead give the user a cookie that stores their language preference. This will be presented next time they visit the site so even the login page can be in their language even though we don't know who they are yet.

Create a middleware that looks if they have locale set in session, and if not, see if they sent a cookie with the locale. If they sent it in a cookie, copy it to the session, then the rest as before.

When they choose the language now, as well as setting it in session, queue a cookie to be sent to them with the response,

2 likes

Please or to participate in this conversation.