Is this code running in the context of a user session?
Oct 10, 2023
6
Level 1
Persist session values in StreamedResponse call
Hello everyone, I hope anyone can help me. I´ve got a problem when i want to store values into the session inside a StreamedResponse function.
Let´s see the code:
...
$request->session()->push('test', '1234');
return response()->stream(function () use ($request) {
$apiResponse = <external API call>
foreach ($apiResponse as $response) {
if (connection_aborted()) {
break;
}
echo "event: message\n";
echo 'data: ' . $repsonse;
echo "\n\n";
ob_flush();
flush();
}
$request->session()->push('test', '5678');
var_dump($request->session()->get('test');
echo "event: message\n";
echo 'data: <END_STREAMING_SSE>';
echo "\n\n";
ob_flush();
flush();
}, 200, [
'Cache-Control' => 'no-cache',
'X-Accel-Buffering' => 'no',
'Content-Type' => 'text/event-stream',
]);
When i call the function, everything seems to be right and i get the following output:
array (size=2)
0 => string '1234' (length=4)
1 => string '5678' (length=4)
But when i look into the session in a second request, i only get the following output.
array (size=1)
0 => string '1234' (length=4)
I tryied it in different ways, but everytime i get the same result. Why weren't the values from the second push() call saved into the session?
Please or to participate in this conversation.