I’ve been struggling with finding the reason for sessions not saving randomly (and often).
In my case the session is saved on page load:
// in the controller
public function some_view(Request $request)
{
$request->session()->put('key1', 'value1');
// ... some more code...
return view(...);
}
Then on another page or function somewhere when I try to get the key1
value it is null
:
// in another method in the project, maybe another controller or mail function
class SomeEmail extends Mailable
{
public $some_value;
public function __construct() {
$this->some_value = session('key1'); // but it's null very often (but not always)
}
}
Then I came across this post of a very old Laravel version (v4): /a/37409073/10847401
which suggests to use the save()
method when I put values:
public function some_view(Request $request)
{
$request->session()->put('key1', 'value1');
$request->session()->save(); // <-- added this
// ... some more code...
return view(...);
}
The save()
method is not in the docs but it still exists in the API for Laravel 10: https://laravel.com/api/10.x/Illuminate/Contracts/Session/Session.html#method_save
And from some reason that worked and there are no longer times where the session value is null in that case
My Laravel project was updated from Version 7 to 10 gradually so maybe that could have also caused some issues?
6