[英]Laravel Session Facade unexpected behaviour
在我的Laravel 5.4项目中,我试图像这样在控制器方法中存储状态令牌。
use Illuminate\Support\Facades\Session ;
...
public function authorize()
{
Session::set('state', $client->getState());
A lot of code here...
header('Location: ' . $authorizationUrl);
exit;
}
我也尝试使用辅助功能
session('state', $client->getState());
但是,无论我尝试了什么,会话都不会创建或持续。
所以我转而直接使用Symfony组件。
use Symfony\Component\HttpFoundation\Session\Session;
...
public function authorise()
{
$session = new Session();
$session->set('state', $client->getState());
...
}
以这种方式做的完美。 任何解释为什么立面不起作用?
作为参考,如果其他任何人遇到这样的问题,则该问题是由重定向,到oauth url,在函数完成之前或加载视图之前引起的。(即,会话存储在Laravel的末尾)应用程序“生命周期”。)此问题可能会在除重定向之外的许多情况下显现,包括使用dd()
或die()
等。
例如,如果您的方法基本上像这样,则Sessions可以正常工作。
public function myAwesomeMethod($params)
{
Session::put('theKey','theValue');
return view('theView'); //Session gets stored at this point.
}
但是,如果您的方法看起来像这样,您将遇到问题。
public function myCoolMethod($authUrl)
{
Session::put('theKey','theValue');
header('Location: ' . $authUrl); //Session seems to be lost here.
exit;
}
解决方案很简单,但是由于我不熟悉Laravel会议,所以我错过了它。 在最后一个示例中,只需将save()
方法添加到Sessions类(如果使用Facade),如下所示。
public function myCoolMethod($authUrl)
{
Session::put('theKey','theValue');
Session::save();// Session gets stored immediately
header('Location: ' . $authUrl);
exit;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.