PHPackages                             nerdofcode/laravel-sse - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. nerdofcode/laravel-sse

ActiveLibrary[API Development](/categories/api)

nerdofcode/laravel-sse
======================

Server-Sent Events (SSE) library for Laravel

1.0.0(7mo ago)213MITPHPPHP ^8.2CI passing

Since Oct 2Pushed 7mo agoCompare

[ Source](https://github.com/NerdOfCode/laravel-SSE)[ Packagist](https://packagist.org/packages/nerdofcode/laravel-sse)[ RSS](/packages/nerdofcode-laravel-sse/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (5)Versions (2)Used By (0)

Laravel SSE (Server-Sent Events)
================================

[](#laravel-sse-server-sent-events)

A simple Server-Sent Events (SSE) library for Laravel apps.

🚀 Quick Start
-------------

[](#-quick-start)

**Try it now without installing Laravel:**

```
./start.sh
# Or manually: php -S localhost:8000 server.php
```

Then open  in your browser!

See [QUICKSTART.md](QUICKSTART.md) for more details.

Features
--------

[](#features)

- Easy integration with Laravel
- Fluent API for sending events
- Support for event types and IDs
- Auto-reconnection handling
- Connection status monitoring
- JSON and text event support
- Keep-alive comments
- Configurable retry times
- Multiple usage patterns

Installation
------------

[](#installation)

Install via Composer:

```
composer require nerdofcode/laravel-sse
```

The package will automatically register its service provider.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --tag=sse-config
```

This will create `config/sse.php` where you can configure default settings.

Basic Usage
-----------

[](#basic-usage)

### Method 1: Using the Facade

[](#method-1-using-the-facade)

```
use LaravelSSE\Facades\SSE;

Route::get('/stream', function () {
    return SSE::create(function () {
        return ['time' => now()->toDateTimeString()];
    }, 1); // Sends event every 1 second
});
```

### Method 2: Using Dependency Injection

[](#method-2-using-dependency-injection)

```
use LaravelSSE\SSE;

Route::get('/stream', function (SSE $sse) {
    return $sse->stream(function (SSE $sse) {
        $counter = 0;

        while ($sse->isConnected() && $counter < 10) {
            $sse->json(['count' => ++$counter]);
            sleep(1);
        }
    });
});
```

### Method 3: Using the Helper

[](#method-3-using-the-helper)

```
Route::get('/stream', function () {
    return app('sse')->stream(function ($sse) {
        $sse->message('Hello World!');
    });
});
```

API Reference
-------------

[](#api-reference)

### Creating Streams

[](#creating-streams)

#### `stream(callable $callback)`

[](#streamcallable-callback)

Create a custom SSE stream with full control:

```
SSE::stream(function (SSE $sse) {
    while ($sse->isConnected()) {
        $sse->event('data', 'event-name', 'event-id');
        sleep(1);
    }
});
```

#### `create(callable $generator, int $interval = 1)`

[](#createcallable-generator-int-interval--1)

Create a simple auto-streaming SSE response:

```
SSE::create(function () {
    return ['data' => 'value'];
}, 2); // Send every 2 seconds
```

### Sending Events

[](#sending-events)

#### `event(string $data, ?string $event = null, ?string $id = null)`

[](#eventstring-data-string-event--null-string-id--null)

Send a custom event:

```
$sse->event('Message content', 'message', '123');
```

#### `message(string $data, ?string $id = null)`

[](#messagestring-data-string-id--null)

Send a simple message (alias for event with data only):

```
$sse->message('Hello World', '123');
```

#### `json(array|object $data, ?string $event = null, ?string $id = null)`

[](#jsonarrayobject-data-string-event--null-string-id--null)

Send JSON data:

```
$sse->json(['user' => 'John', 'status' => 'active'], 'user-update', '456');
```

#### `comment(string $comment)`

[](#commentstring-comment)

Send a comment (keeps connection alive):

```
$sse->comment('Keep-alive');
```

### Configuration Methods

[](#configuration-methods)

#### `setRetry(int $milliseconds)`

[](#setretryint-milliseconds)

Set reconnection retry time:

```
SSE::setRetry(5000)->stream(...);
```

#### `setEventId(?string $id)`

[](#seteventidstring-id)

Set default event ID:

```
SSE::setEventId('stream-1')->stream(...);
```

#### `setHeader(string $key, string $value)`

[](#setheaderstring-key-string-value)

Add custom header:

```
SSE::setHeader('X-Custom', 'value')->stream(...);
```

#### `setExecutionTime(int $seconds)`

[](#setexecutiontimeint-seconds)

Set maximum execution time (0 = unlimited):

```
SSE::setExecutionTime(300)->stream(...);
```

### Utility Methods

[](#utility-methods)

#### `isConnected()`

[](#isconnected)

Check if client is still connected:

```
while ($sse->isConnected()) {
    // Send events
}
```

#### `stop()`

[](#stop)

Stop the stream:

```
$sse->stop();
```

Client-Side (JavaScript)
------------------------

[](#client-side-javascript)

```
const eventSource = new EventSource('/stream');

// Listen to all messages
eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
};

// Listen to specific event types
eventSource.addEventListener('custom-event', (event) => {
    const data = JSON.parse(event.data);
    console.log('Custom event:', data);
});

// Handle errors
eventSource.onerror = (error) => {
    console.error('SSE Error:', error);
};

// Close connection
eventSource.close();
```

Examples
--------

[](#examples)

### Real-time Counter

[](#real-time-counter)

```
Route::get('/counter', function () {
    return SSE::create(function () use (&$counter) {
        static $counter = 0;
        return ['count' => ++$counter];
    });
});
```

### Progress Monitor

[](#progress-monitor)

```
Route::get('/progress', function () {
    return SSE::stream(function (SSE $sse) {
        for ($i = 0; $i json([
                'progress' => $i,
                'status' => $i < 100 ? 'processing' : 'complete'
            ], 'progress');
            sleep(1);
        }
    });
});
```

### Live Notifications

[](#live-notifications)

```
Route::get('/notifications', function (Request $request) {
    $userId = $request->user()->id;

    return SSE::stream(function (SSE $sse) use ($userId) {
        $lastCheck = now();

        while ($sse->isConnected()) {
            $notifications = Notification::where('user_id', $userId)
                ->where('created_at', '>', $lastCheck)
                ->get();

            foreach ($notifications as $notification) {
                $sse->json($notification, 'notification', $notification->id);
            }

            $lastCheck = now();
            sleep(2);
        }
    });
});
```

Testing
-------

[](#testing)

The package includes a comprehensive test suite.

### Running Tests

[](#running-tests)

```
# Install dependencies
composer install

# Run all tests
composer test

# Run with coverage report
composer test-coverage

# Run specific test suite
./vendor/bin/phpunit tests/Unit
./vendor/bin/phpunit tests/Feature
```

### Test Coverage

[](#test-coverage)

- ✅ SSE class methods and configuration
- ✅ Event formatting and output
- ✅ Service provider registration
- ✅ Facade functionality
- ✅ Integration tests for streaming
- ✅ Standalone SSE implementation

See [tests/README.md](tests/README.md) for more details.

Configuration
-------------

[](#configuration)

Edit `config/sse.php`:

```
return [
    'retry' => env('SSE_RETRY', 3000), // Retry time in ms
    'execution_time' => env('SSE_EXECUTION_TIME', 0), // Max execution time
];
```

Or use `.env`:

```
SSE_RETRY=5000
SSE_EXECUTION_TIME=300
```

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0
- Laravel &gt;= 9.0

License
-------

[](#license)

MIT License

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance63

Regular maintenance activity

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

228d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/800f325cee93d2f7816bdaabe590bbaefc20ffb17a816672ff2ca226af9e6dff?d=identicon)[nerdofcode](/maintainers/nerdofcode)

---

Top Contributors

[![NerdOfCode](https://avatars.githubusercontent.com/u/19696288?v=4)](https://github.com/NerdOfCode "NerdOfCode (4 commits)")

---

Tags

laravelstreamingsseserver sent events

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nerdofcode-laravel-sse/health.svg)

```
[![Health](https://phpackages.com/badges/nerdofcode-laravel-sse/health.svg)](https://phpackages.com/packages/nerdofcode-laravel-sse)
```

###  Alternatives

[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[resend/resend-laravel

Resend for Laravel

1191.4M6](/packages/resend-resend-laravel)[joggapp/laravel-aws-sns

Laravel package for the SNS events by AWS

3171.8k](/packages/joggapp-laravel-aws-sns)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[surface/laravel-webfinger

A Laravel package to create an ActivityPub webfinger.

113.8k](/packages/surface-laravel-webfinger)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
