Scarass
Scarass

Reputation: 944

Session data gets destroyed

This is the code where I store some data into session:

class SiteController extends Controller
{
    function changeLang($lang){
        //session(["lang"=>$lang]);
        session()->put('lang', $lang);
        dump(session()->all());  // variable lang is inside session
        return Redirect::back();
    }
}

Data gets successfully written into session, I know because dump prints it. Right now I'm trying to use session()->put, and I've also tried session($array).

And when I try to read all the data from it (with the code below), I get an empty array.

class MyMiddleware
{
    public function handle($request, Closure $next)
    {
        dump(session()->all());  // I get an empty array here
        return $next($request);
    }
}

And here's my session.php (not that I've changed anything):

return [

    'driver' => env('SESSION_DRIVER', 'file'),   
    'lifetime' => 120,
    'expire_on_close' => false,    
    'encrypt' => false,    
    'files' => storage_path('framework/sessions'),       
    'connection' => null,  
    'table' => 'sessions',   
    'store' => null,    
    'lottery' => [2, 100],   
    'cookie' => 'laravel_session',   
    'path' => '/',    
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => env('SESSION_SECURE_COOKIE', false),        
    'http_only' => true,

];

I've deleted all the comments from so its easier for you to see important stuff.

So yeah, my session gets emptied somehow.

Upvotes: 1

Views: 64

Answers (2)

Rahi
Rahi

Reputation: 1485

Go to your app/Http/Kernel.php and with $middlewareGroup variable add your middleware after StartSession. See below...

\Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\MyMiddleware::class,

Upvotes: 2

yan_n
yan_n

Reputation: 31

You should load your middleware after the StartSession middleware.

Upvotes: 1

Related Questions