Laravel Session Facade unexpected behaviour

3.5k Views Asked by At

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.

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.

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

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