Download the PHP package sinemacula/laravel-sse without Composer
On this page you can find all versions of the php package sinemacula/laravel-sse. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download sinemacula/laravel-sse
More information about sinemacula/laravel-sse
Files in sinemacula/laravel-sse
Package laravel-sse
Short Description Server-Sent Events (SSE) streaming primitives for Laravel - an event stream response with a heartbeat polling loop and a typed emitter.
License Apache-2.0
Informations about the package laravel-sse
Laravel SSE
[](https://packagist.org/packages/sinemacula/laravel-sse)
[](https://packagist.org/packages/sinemacula/laravel-sse)
[](https://packagist.org/packages/sinemacula/laravel-sse)
[](https://github.com/sinemacula/laravel-sse/actions/workflows/tests.yml)
[](https://github.com/sinemacula/laravel-sse/actions/workflows/quality-gates.yml)
[](https://qlty.sh/gh/sinemacula/projects/laravel-sse)
[](https://qlty.sh/gh/sinemacula/projects/laravel-sse)
[](https://packagist.org/packages/sinemacula/laravel-sse)
[](LICENSE)
Server-Sent Events (SSE) streaming primitives for Laravel - an event stream response built around a heartbeat polling
loop and a typed emitter. Drop the EventStream into any class, or mix the RespondsWithEventStream trait into a
controller, and stream text/event-stream responses without hand-assembling the SSE wire format.
The package ships no service provider, no config file, and no artisan commands - it is a small set of primitives you compose into your own endpoints.
How It Works
An EventStream owns the transport lifecycle: it builds a StreamedResponse with the required SSE headers, runs a
polling loop, emits keep-alive heartbeats, watches for client disconnects, and handles callback errors. On each poll it
invokes your callback - optionally handing it an Emitter - then sleeps for the configured interval before polling
again.
The Emitter writes the SSE wire format for you: emit() produces data: blocks (JSON-encoding arrays and splitting
multi-line strings across separate data: fields), optionally preceded by an event: field, and comment() writes the
: keep-alive lines.
A few rules hold across the surface:
- Unbounded by default. With no ceiling configured the loop runs until the client disconnects - exactly the
behaviour you want under php-fpm. Set
maxDurationormaxIterationsto make a stream self-terminate gracefully (see Running SSE under Octane). - Extensible through protected hooks. Subclass
EventStreamand overrideonStreamStart(),onStreamEnd(), orshouldContinueAfterError()to customise lifecycle behaviour.onStreamEnd()receives aStreamTerminationReasonso you can tell a graceful ceiling-reached close from a client disconnect or an error. - No framework coupling beyond Laravel's helpers. The trait accepts a plain integer HTTP status, so a consuming controller is not forced to depend on any particular enum or base-controller library.
Installation
No service provider registration is required. The package ships no artisan commands or config files.
Usage
Standalone - from any class
In a controller - via the trait
The trait exposes heartbeatInterval(), maxStreamDuration(), and maxStreamIterations() as overridable protected
methods. (They are methods, not constants: a using class cannot override a trait constant in PHP 8.2+.)
Extending EventStream
Override the protected hooks to customise lifecycle behaviour. onStreamEnd() receives a StreamTerminationReason
so you can tell a graceful ceiling-reached close from a client disconnect or an error:
Running SSE under Octane
Under php-fpm each request owns its own process, so a long-lived stream is tolerable - the process dies at request end.
Under Laravel Octane (Swoole / RoadRunner) the worker pool is fixed and shared, and the EventStream poll loop holds
one worker for the entire lifetime of a connection. A single connection the client never closes pins that worker
indefinitely, and enough concurrent connections exhaust the pool and starve unrelated API traffic.
- Set a ceiling under Octane. Configure
maxStreamDuration()(or themaxDurationconstructor argument) so each stream self-terminates and returns its worker to the pool even if the client never disconnects. A starting point of 300 seconds is reasonable for most Octane deployments; tune it to your worker count and traffic. The cap fires before Octane's ownmax_execution_timeSIGKILL, so the close is graceful rather than a killed worker. The ceiling is enforced regardless of the polling interval: the final sleep before the deadline is shortened to the time remaining, so a longintervalcannot hold the worker pastmaxDuration. - The default is unbounded. With no ceiling set the loop runs until the client disconnects, exactly as under php-fpm - opt in to a ceiling; it is never imposed.
- Offload high-concurrency streaming. A self-terminating poll loop bounds a single stream, but it does not turn the worker model into a broadcast hub. For many concurrent connections at scale, offload to a dedicated connection layer (Laravel Reverb, Mercure, or a websocket server) that holds the persistent connections rather than relying on the poll loop.
API
EventStream
| Method | Description |
|---|---|
__construct(int $heartbeatInterval = 20, int $maxDuration = 0, int $maxIterations = 0) |
Construct a stream. maxDuration (seconds) and maxIterations are ceilings after which the stream self-terminates; 0 means unbounded. |
toResponse(callable $callback, int $interval = 1, int $status = 200, array $headers = []) |
Build and return a StreamedResponse with SSE headers and polling loop. |
onStreamStart(Emitter $emitter) (protected) |
Called once before the polling loop; emits the initial keep-alive by default. |
onStreamEnd(StreamTerminationReason $reason) (protected) |
Called after the loop exits, with the reason it ended; empty by default. |
shouldContinueAfterError(\Throwable, Emitter) (protected) |
Called on callback exception; returns false to stop, true to continue. |
StreamTerminationReason
A string-backed enum passed to onStreamEnd(): CLIENT_DISCONNECT, ERROR, MAX_DURATION, MAX_ITERATIONS.
Emitter
| Method | Description |
|---|---|
emit(array\|string $data, ?string $event = null) |
Write a data: block (optionally preceded by event:). Arrays are JSON-encoded. |
comment(string $text = '') |
Write a keep-alive comment line. |
RespondsWithEventStream trait
| Method | Description |
|---|---|
respondWithEventStream(callable $callback, int $interval = 1, int $status = 200, array $headers = []) |
Convenience wrapper around EventStream::toResponse(). |
heartbeatInterval() / maxStreamDuration() / maxStreamIterations() (protected) |
Override to configure the heartbeat cadence and the stream ceilings. Default to 20 / 0 / 0. |
Validation and errors
- Negative timing values are rejected: the
EventStreamconstructor andtoResponse()throwInvalidArgumentExceptionon a negativeheartbeatInterval,maxDuration,maxIterations, orinterval.0is accepted as the documented unbounded (ceilings) / no-delay (interval) sentinel. The same applies to negative returns from the trait'sheartbeatInterval()/maxStreamDuration()/maxStreamIterations()seams. - A
heartbeatIntervalof0is not "heartbeats off" - it means a zero-second interval, so a keep-alive comment is emitted on every poll. Leave it at the default (or any positive value) for normal cadence; there is no disable sentinel because a stream with no keep-alive would defeat the proxy-timeout protection the heartbeat exists to give. - The constructor parameter order is stable as of 1.0; passing arguments by name -
new EventStream(maxDuration: 300)- reads more clearly and is recommended over positional arguments. Emitter::emit()throwsJsonExceptionif array data cannot be encoded (for example, invalid UTF-8); the polling loop routes that throughshouldContinueAfterError(). CR/LF in an event name or comment text is stripped to prevent SSE field injection.
Requirements
- PHP ^8.3
- Laravel (illuminate/support) ^12.9
Testing
Changelog
See CHANGELOG.md for a list of notable changes.
Contributing
Contributions are welcome. Please read CONTRIBUTING.md for guidelines on branching, commits, code quality, and pull requests.
Security
If you discover a security vulnerability, please report it responsibly. See SECURITY.md for the disclosure policy and contact details.
License
Licensed under the Apache License, Version 2.0.
All versions of laravel-sse with dependencies
illuminate/support Version ^12.9|^13.0
symfony/http-foundation Version ^7.2