Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged

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
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.

2 participants