Skip to content

Conversation

@devhammed
Copy link
Contributor

[12.x] Enhance eventStream to Support Custom Events and Start Messages

Summary

⚠️ BREAKING CHANGE: This PR changes the eventStream method in ResponseFactory by allowing customization of:

  • Event Name ($as) – Previously hardcoded as "update", now configurable and the generator function can now yield Illuminate\Http\EventStream to customize the name per stream.
  • Start Stream Message ($startStreamWith) – Optional message sent before streaming begins.
  • End Stream Message ($endStreamWith) – Now optional instead of required.

Why This Change?

  • More Flexible SSE Handling: Developers can now specify custom event names, making it easier to differentiate between different types of SSE messages and also they can now decide if they want start/end messages.
  • Improved Client Communication: Some clients expect an initial message when connecting. The $startStreamWith parameter allows for this.

Implementation Details

The method signature now includes:

public function eventStream(
    Closure $callback, 
    array $headers = [], 
    string $as = 'update', 
    ?string $startStreamWith = null, 
    ?string $endStreamWith = '</stream>'
) {}

This has also been updated to fix the issue raised in the last PR:

Reverted this PR. The update "as" name should be customizable per update, not for the entire event stream.

I have added a data class that the generator function can yield to override the function $as parameter.

use App\Models\User;
use Illuminate\Http\EventStream;

Route::get('/users', function () {
    return response()->eventStream(function () {
        $notifications = Notification::all();

        foreach ($notifications as $notification) {
            yield new EventStream(
		        event: 'notification',
                data: $notification->toJson(),
            );
            sleep(1);
        }
    }, startStreamWith: '[', endStreamWith: ']');
});

@taylorotwell taylorotwell merged commit 006a627 into laravel:12.x Feb 25, 2025
39 checks passed
@devhammed devhammed deleted the feat-enhance-event-stream-response branch February 26, 2025 02:52
@ivan-plotnikov
Copy link

Thank you! I've really needed this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants