Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

php - Laravel session data not sticking across page loads

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  1. Store a value in session without killing the script.

    Route::get('test', function() {
        Session::put('progress', '5%');
        // dd(Session::get('progress'));
    });
    
  2. Retrieve the value already stored:

    Route::get('test', function() {
        // Session::put('progress', '5%');
        dd(Session::get('progress'));
    });
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...