Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

M304's avatar
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?

0 likes
6 replies
Snapey's avatar

Is this code running in the context of a user session?

M304's avatar
Level 1

Yes, only authenticated users can access the function

jlrdw's avatar

@M304 apply authorization, either a gate or a policy.

M304's avatar
Level 1

I use the breeze starter kit. The route secured by default "auth" middleware.

jlrdw's avatar

@M304

I use the breeze starter kit. The route secured by default "auth" middleware.

Authentication means a login. You need authorization to tell a method if the logged in user can or cannot do something.

Proper authentication and authorization is a steep learning curve, I suggest learn it correctly. It is easier once learned.

M304's avatar
Level 1

@jlrdw Thanks for the clarification.

As suggested, I added a gate authentication. However, the result remains the same.

Please or to participate in this conversation.