Laravel会话数据不会在页面加载中停留 [英] Laravel session data not sticking across page loads
问题描述
我尝试运行以下代码:
Session::put('progress', '5%');
dd(Session::get('progress'));
这将在转储中显示'5%'.
如果我重新运行同一页面但注释掉Session::put('progress', '5%');
,以便仅调用dd()
行,则会得到一个空值,而不是前一页加载时存储的5%.
这是我的会话配置,所以我知道它应该存储数据:
'driver' => 'native',
'lifetime' => 120,
'expire_on_close' => false,
Laravel为什么不跨页面加载存储会话数据?
问题是因为您在Laravel完成其应用程序生命周期之前就杀死了脚本,所以会话中(但尚未存储)的值也被杀死了. /p>
当Laravel应用程序生命周期开始时,在应用程序生命周期结束之前,Session
中的任何值put
都不会被存储.那就是当Session
中的任何put
值最终/真正成为stored
时.
如果您检查来源,则您会发现相同的上述行为:
public function put($key, $value)
{
$all = $this->all();
array_set($all, $key, $value);
$this->replace($all);
}
如果要测试,请执行以下操作:
-
在会话中存储一个值,而不会终止该脚本.
Route::get('test', function() { Session::put('progress', '5%'); // dd(Session::get('progress')); });
-
检索已存储的值:
Route::get('test', function() { // Session::put('progress', '5%'); dd(Session::get('progress')); });
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')); });
这篇关于Laravel会话数据不会在页面加载中停留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!