dd()是laravel中非常常用的一个函数,有debug神器的称号。
但是今天与session一起使用碰到到了问题。session内容存不住。
问题复现
public function test002(Request $request){
$request->session()->push('key','rrr');
$info = $request->session()->get('key');
dd($info);
}
// 输出结果
array:1 [▼
0 => "rrr"
]
看了运行结果原以为储存成功了,但是去其他方法获取发现是null,本地使用file储存session,发现根本没有生成缓存文件,看来是被它的运行结果迷惑了。
public function test002(Request $request){
$request->session()->push('key','rrr');
$info = $request->session()->get('key');
var_dump($info);
}
接下来使用这种方法,session储存成功,生成了缓存文件。
问题猜想
session()的储存放在后置的中间件中,dd()断点了,导致储存失败。
问题验证
先造一个中间件,验证dd()是否会阻断后置中间件。
public function handle($request, Closure $next)
{
echo '前置';
$response = $next($request);
echo '后置';
return $response;
}
//输出结果
前置
找到 \Illuminate\Session\Middleware\StartSession::class 这个中间件
public function handle($request, Closure $next)
{
$this->sessionHandled = true;
// If a session driver has been configured, we will need to start the session here
// so that the data is ready for an application. Note that the Laravel sessions
// do not make use of PHP "native" sessions in any way since they are crappy.
if ($this->sessionConfigured()) {
$request->setLaravelSession(
$session = $this->startSession($request)
);
$this->collectGarbage($session);
}
$response = $next($request);
// Again, if the session has been configured we will need to close out the session
// so that the attributes may be persisted to some storage medium. We will also
// add the session identifier cookie to the application response headers now.
if ($this->sessionConfigured()) {
$this->storeCurrentUrl($request, $session);
$this->addCookieToResponse($response, $session); //在这里进行的储存
}
return $response;
}