且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 5 - 会话不起作用

更新时间:2023-08-22 22:10:46

Laravel 5 通过名为 StartSession 的中间件类处理会话.更重要的是,这个中间件是一个 TerminableMiddleware 并且实际保存数据(在你的例子中保存到会话文件)的代码位于 terminate 方法中,该方法运行于请求生命周期结束:

public function terminate($request, $response){if ($this->sessionHandled && $this->sessionConfigured() && ! $this->usingCookieSessions()){$this->manager->driver()->save();}}

当调用dd(Session::get('aa'));时,请求在中间件的terminate方法被调用之前被中断.>

有趣的是,Laravel Middleware Documentation 实际上通过给 Laravel 解释了可终止中间件的逻辑StartSession 中间件为例:

例如,Laravel 包含的会话"中间件在响应发送到浏览器后将会话数据写入存储.

话虽如此,请尝试使用 var_dump() 而不是 dd().

Here's config/session.php:

return [
    'driver' => 'file',
    'files' => storage_path().'/framework/sessions',
];

My storage/framework/sessions have 755 permissions.

When I put these 2 line in my controller

Session::set('aa', 'bb');
dd(Session::get('aa'));

I receive expected "bb" output. But if I comment first line:

// Session::set('aa', 'bb');
dd(Session::get('aa'));

and refresh page, I still expecting "bb" but getting null.

Also, storage/framework/sessions is empty.

What should I do to make Session working?

Laravel 5 handles sessions via a middleware class called StartSession. More importantly, this middleware is a TerminableMiddleware and the code that actually saves the data (in your case to the session file) is located in the terminate method, which is run at the end of the request lifecycle:

public function terminate($request, $response)
{
    if ($this->sessionHandled && $this->sessionConfigured() && ! $this->usingCookieSessions())
    {
        $this->manager->driver()->save();
    }
}

When calling dd(Session::get('aa')); the request is being interrupted before the terminate method of the middleware can be called.

Funnily enough, the Laravel Middleware Documentation actually explains Terminable Middleware logic by giving the Laravel StartSession middleware as an example:

For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser.

That being said, try using var_dump() instead of using dd().