I tried running the following code:
Session::put('progress', '5%');
dd(Session::get('progress'));
This will show '5%' in the dump.
If I rerun the same page but comment out Session::put('progress', '5%');
so that only the dd()
line is called, I get a null value instead of the 5% values stored in the previous page load.
Here is my sessions config, so I know it should be storing the data:
'driver' => 'native',
'lifetime' => 120,
'expire_on_close' => false,
Why is Laravel not storing the session data across page loads?
The problem is because you are killing the script before Laravel finishes its application lifecycle, so the values put in session (but not yet stored) got killed too.
When a Laravel application lifecycle starts, any value put
in Session
are not yet stored until the application lifecycle ends. That is when any value put
in Session
will be finally/really stored
.
If you check the source you will find the same aforementioned behavior:
public function put($key, $value)
{
$all = $this->all();
array_set($all, $key, $value);
$this->replace($all);
}
If you want to test it, do the following:
Store a value in session without killing the script.
Route::get('test', function() {
Session::put('progress', '5%');
// dd(Session::get('progress'));
});
Retrieve the value already stored:
Route::get('test', function() {
// Session::put('progress', '5%');
dd(Session::get('progress'));
});
Rubens Mariuzzo's answer is very good. I just want to add that if you need the data to be stored immediately you could use the save method:
Session::put('progress', '5%');
Session::save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With