Laravel 5-会话无效 [英] Laravel 5 - session doesn't work

查看:62
本文介绍了Laravel 5-会话无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是config/session.php:

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

我的storage/framework/sessions具有755权限.

当我将这两行放入控制器时

When I put these 2 line in my controller

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

我收到预期的"bb"输出.但是,如果我评论第一行:

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

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

和刷新页面,我仍然期望"bb",但得到null.

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

此外,storage/framework/sessions为空.

我该怎么做才能使Session工作?

What should I do to make Session working?

推荐答案

Laravel 5通过称为StartSession的中间件类处理会话.更重要的是,此中间件是TerminableMiddleware,而实际上保存数据(在您的情况下为会话文件)的代码位于terminate方法中,该方法在请求生命周期的结尾运行:

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();
    }
}

在调用dd(Session::get('aa'));时,请求被中断,然后才能调用中间件的terminate方法.

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

很有趣的是, Laravel中间件文档实际上通过给Laravel StartSession解释了终止中间件的逻辑.中间件为例:

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

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

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

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

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

这篇关于Laravel 5-会话无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆