Search code examples
laravelsessionhttp-redirectsession-variables

Laravel 7 session values not retained after redirect


I am trying to set a session in Laravel 7 that will remember what language the website should be displayed in

On my routes I have

Route::get('set-locale/{locale}', function ($locale) {
    if (!in_array($locale, ['en', 'nl'])) {
        // todo: return with flash
    }

    \Illuminate\Support\Facades\Session::put('locale', $locale);

    // the session is set here

    return back();
})->name('set-locale');

I have a middleware that is part of the 'web' middlewares. I can see it is used on every page load, but the required value is not there

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        Locale::class
    ],
class Locale
{
    public function handle(Request $request, Closure $next, $guard = null)
    {
        dump(Session::all()); // I can see the login info here, not the locale
        if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }

        return $next($request);
    }
}

I did not change the config for the sessions, so it is using the default settings

'driver' => env('SESSION_DRIVER', 'file'),
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,

I looked into using

back()->with('locale', $locale);

But that does not work either, and I also want to retain the value for the duration of the session, not just for the next request

I have been looking at dozens of similar questions here and elsewhere and none of them seem to cover this exact scenario


Solution

  • I have checked your scenario and make the same thing on my laptop. The session is working fine.

    Here is my implementation.

    env file

    BROADCAST_DRIVER=log
    CACHE_DRIVER=file
    SESSION_DRIVER=file
    SESSION_LIFETIME=120
    QUEUE_DRIVER=sync
    

    Middleware

    namespace App\Http\Middleware;
    
    use Closure;
    use Session;
    
    class Locale
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next, $guard = null)
        {
            dump(Session::all()); // I can see the login info here, not the locale
            if (Session::has('locale')) {
                \App::setLocale(Session::get('locale'));
            }
    
            return $next($request);
        }
    }
    

    Kernel.php

    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Locale::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],
        ...
    ];
    

    Routes

    Route::get('/', function () {
        return view('welcome');
    });
    
    
    Route::get('set-locale/{locale}', function ($locale) {
        if (!in_array($locale, ['en', 'nl'])) {
            // todo: return with flash
        }
    
        \Illuminate\Support\Facades\Session::put('locale', $locale);
    
        // the session is set here
    
        return back();
    })->name('set-locale');
    

    When I open the URL the first time it shows me the following result.

    request without settion session

    but when I open URL

    set-locale/en

    then the "en" is set on the session and further request gives me the following output.

    enter image description here

    Note:- You may need to clear the content of the session folder "\storage\framework\sessions" to clear the sessions things.