Laravel Session Facade意外行为 [英] Laravel Session Facade unexpected behaviour

查看:64
本文介绍了Laravel Session Facade意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Laravel 5.4项目中,我试图像这样在控制器方法中存储状态令牌.

In my Laravel 5.4 project I was trying to store a state token in my controller method like this..

 use Illuminate\Support\Facades\Session ;
 ... 
 public function authorize()
 {
    Session::set('state', $client->getState());

       A lot of code here...

    header('Location: ' . $authorizationUrl);
        exit;
 }

我也尝试过使用辅助功能

I also tried using the helper function

  session('state', $client->getState());

但是无论我尝试了什么,会话都不会创建或持续.

But no matter what I've tried the session would not be created or persist.

所以我转而直接使用Symfony组件.

So I switched to using the Symfony component directly..

use Symfony\Component\HttpFoundation\Session\Session;
...
public function authorise()
{
   $session = new Session();
   $session->set('state', $client->getState());
   ...
}

以这种方式进行操作非常完美.为什么外墙无法正常工作?

Doing it this way works perfectly. Any explanation why the facade is not working?

推荐答案

作为参考,如果其他任何人遇到这样的问题,则该问题是由函数完成之前重定向到oauth url引起的,或者视图已加载等.(即,会话存储在Laravel应用程序生命周期"的末尾.)除了重定向以外,此问题还可以在许多情况下显示出来,包括使用 dd() die()等.

As a reference if anyone else has an issue like this, the issue was being caused by a redirect, to an oauth url, before the function finishes, or a view was loaded etc. (i.e. the session gets stored at the end of the Laravel application "lifecycle".) This issue can manifest itself in any number of situations other than just a redirect, including using dd() or die()etc.

例如如果您的方法基本上像这样,则Sessions可以正常工作.

e.g. If your method is basically like this Sessions works fine.

public function myAwesomeMethod($params)
{
    Session::put('theKey','theValue');

    return view('theView'); //Session gets stored at this point.
}

但是,如果您的方法看起来像这样,则会出现问题.

However if your method looks like something like this you will have an issue.

public function myCoolMethod($authUrl)
{
    Session::put('theKey','theValue');

    header('Location: ' . $authUrl); //Session seems to be lost here.
    exit;
}

解决方案很简单,但是由于我不熟悉Laravel会议,所以我错过了它.在最后一个示例中,只需将 save()方法添加到Sessions类(如果使用Facade),如下所示.

The solution was simple but I missed it because of my unfamiliarity with the Laravel sessions. In the last example simply add the save() method to the Sessions class (if using the Facade) like in the following.

public function myCoolMethod($authUrl)
{
     Session::put('theKey','theValue');
     Session::save();// Session gets stored immediately

     header('Location: ' . $authUrl); 
     exit;
 }

这篇关于Laravel Session Facade意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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