Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Reverb Laravel Package

laravel/reverb

Laravel Reverb adds real-time WebSocket communication to Laravel apps. Use it to broadcast events and power live updates with a first-party, Laravel-native server. Official docs: https://laravel.com/docs/reverb

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/reverb
    php artisan reverb:install
    

    This generates the Reverb configuration and publishes assets.

  2. Configuration: Update .env with Redis connection details:

    BROADCAST_CONNECTION=redis
    REVERB_REDIS_URL=redis://localhost:6379
    REVERB_HOST=127.0.0.1
    REVERB_PORT=8080
    
  3. First Use Case: Broadcast an event to a channel:

    use Illuminate\Broadcasting\Channel;
    use Illuminate\Support\Facades\Broadcast;
    
    Broadcast::channel('chat', function ($user) {
        return ['id' => $user->id];
    });
    
    // In a controller or command
    Broadcast::to('chat')->send(new ChatMessage('Hello!'));
    
  4. Client-Side Connection: Use the laravel-echo package with Reverb:

    import Echo from 'laravel-echo';
    
    window.Pusher = require('pusher-js');
    
    window.Echo = new Echo({
        broadcaster: 'reverb',
        key: 'your-app-key',
        wsHost: window.location.hostname,
        wsPort: 8080,
        forceTLS: false,
        disableStats: true,
        enabledTransports: ['ws', 'wss'],
    });
    
  5. Run Reverb:

    php artisan reverb:start
    

    Use php artisan reverb:stop and php artisan reverb:restart as needed.


Implementation Patterns

Core Workflows

1. Broadcasting Events

  • Private Channels:
    Broadcast::private('user.123')->send(new UserEvent('Updated!'));
    
  • Presence Channels:
    Broadcast::channel('chat.{room_id}', function ($user, $room) {
        return ['user_id' => $user->id];
    });
    Broadcast::to('chat.123')->send(new ChatEvent('New message'));
    

2. Handling Incoming Events

  • Use BroadcastServiceProvider to register event handlers:
    public function boot()
    {
        Broadcast::route('chat', function ($user, $room) {
            return ['room_id' => $room->id];
        });
    
        Broadcast::route('private-user.{id}', function ($user, $id) {
            return (int) $id === $user->id;
        });
    }
    

3. Scaling with Redis

  • Reverb automatically scales using Redis pub/sub. Configure multiple Reverb instances in config/broadcasting.php:
    'connections' => [
        'redis' => [
            'driver' => 'redis',
            'connection' => 'cache',
            'options' => [
                'cluster' => env('REDIS_CLUSTER', 'redis'),
                'reverb' => [
                    'host' => env('REVERB_HOST', '127.0.0.1'),
                    'port' => env('REVERB_PORT', 8080),
                ],
            ],
        ],
    ],
    

4. Authentication

  • Use Laravel's built-in auth for channels:
    Broadcast::channel('private-user.{id}', function ($user, $id) {
        return (int) $id === $user->id;
    });
    
  • For custom auth, extend ReverbAuthenticator or use middleware:
    Broadcast::route('custom-channel', function ($user, $request) {
        return $request->user()->canAccessChannel();
    });
    

5. Rate Limiting

  • Configure in config/reverb.php:
    'rate_limiting' => [
        'enabled' => true,
        'max_attempts' => 100,
        'decay_seconds' => 60,
    ],
    

6. Customizing Reverb

  • Override the default router or authenticator:
    // app/Providers/ReverbServiceProvider.php
    public function boot()
    {
        $this->app->bind(\Laravel\Reverb\Routing\Router::class, function ($app) {
            return new \App\Reverb\CustomRouter($app);
        });
    }
    

Integration Tips

1. Laravel Echo Integration

  • Ensure laravel-echo is configured to use Reverb:
    window.Echo = new Echo({
        broadcaster: 'reverb',
        key: 'your-app-key',
        wsHost: window.location.hostname,
        wsPort: 8080,
        forceTLS: false,
        enabledTransports: ['ws', 'wss'],
    });
    

2. Vue/React Integration

  • Use laravel-echo with Vue/React:
    // Vue example
    import Echo from 'laravel-echo';
    
    const echo = new Echo({
        broadcaster: 'reverb',
        // ...config
    });
    
    echo.private(`user.${userId}`)
        .listen('UserEvent', (data) => {
            console.log(data);
        });
    

3. Testing

  • Use ReverbTestCase for testing:
    use Laravel\Reverb\Testing\ReverbTestCase;
    
    class ChatTest extends ReverbTestCase
    {
        public function test_chat_broadcast()
        {
            $this->actingAs($user)
                ->assertBroadcastingOn('chat')
                ->broadcast(new ChatMessage('Hello!'));
        }
    }
    

4. Deployment

  • Run Reverb as a service (e.g., with Supervisor):
    [program:reverb]
    command=php /path/to/artisan reverb:start
    autostart=true
    autorestart=true
    user=www-data
    numprocs=1
    redirect_stderr=true
    stdout_logfile=/var/log/reverb.log
    

Gotchas and Tips

Pitfalls

1. Connection Limits

  • Reverb enforces connection limits by default (1000 connections). Adjust in config/reverb.php:
    'connection_limits' => [
        'max_connections' => 5000,
        'max_connections_per_ip' => 100,
    ],
    

2. Redis Cluster Issues

  • Ensure Redis cluster is properly configured. Reverb may fail silently if Redis is unreachable.
  • Test Redis connectivity:
    redis-cli ping
    

3. CORS and Allowed Origins

  • Reverb restricts connections to allowed origins by default. Configure in config/reverb.php:
    'allowed_origins' => [
        'https://your-app.com',
        'http://localhost:3000',
    ],
    
  • Use wildcards for development:
    'allowed_origins' => ['*'],
    

4. Memory Leaks

  • Older versions had memory leaks (fixed in v1.7.0). Ensure you’re using the latest version.
  • Monitor memory usage with php artisan reverb:stats.

5. Custom Server Paths

  • If using a custom server path (e.g., /reverb), ensure:
    • The path is included in the broadcasting config:
      'options' => [
          'reverb' => [
              'host' => env('REVERB_HOST', '127.0.0.1'),
              'port' => env('REVERB_PORT', 8080),
              'path' => env('REVERB_PATH', '/reverb'),
          ],
      ],
      
    • The client uses the correct path:
      wsHost: window.location.hostname,
      wsPort: 8080,
      wsPath: '/reverb',
      

6. Event Data Validation

  • Reverb validates event data payloads. Ensure your events extend ShouldBroadcast and have valid JSON-serializable data:
    class ChatMessage implements ShouldBroadcast
    {
        public function __construct(public string $message) {}
    
        public function broadcastOn(): array
        {
            return ['chat'];
        }
    }
    

7. Presence Channel Quirks

  • Presence channels require proper channel authorization. Ensure your BroadcastServiceProvider routes are correct:
    Broadcast::channel('chat.{room_id}', function ($user, $room) {
        return $user->canAccessRoom($room);
    });
    

Debugging Tips

1. Enable Verbose Logging

  • Add to config/reverb.php:
    'log_level' => 'debug',
    
  • Check logs at storage/logs/reverb.log.

2. Check Redis Pub/Sub

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport