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?
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()
ordie()
etc.e.g. If your method is basically like this Sessions works fine.
However if your method looks like something like this you will have an issue.
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.