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 support to Laravel applications, enabling event broadcasting and live updates via a first-party server. Designed to integrate with Laravel’s broadcasting features for fast, reliable real-time communication.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require laravel/reverb
   php artisan reverb:install

This generates a .env configuration and publishes the necessary files.

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

    BROADCAST_CONNECTION=redis
    REVERB_REDIS_URL=redis://localhost:6379
    REVERB_HOST=127.0.0.1
    REVERB_PORT=6001
    
  2. Run Reverb:

    php artisan reverb:start
    

    For production, use a process manager like Supervisor to keep Reverb running.

  3. First Use Case: Use Laravel's built-in broadcasting to test:

    // In a route or controller
    broadcast(new \App\Events\TestEvent())->toOthers();
    

    Connect via JavaScript:

    const socket = new WebSocket(`ws://${window.location.hostname}:6001/app/TEST_CHANNEL`);
    socket.onmessage = (event) => console.log(event.data);
    

Key Files to Review

  • config/broadcasting.php: Configure broadcasting connections.
  • config/reverb.php: Reverb-specific settings (e.g., host, port, heartbeat).
  • routes/channels.php: Define channel authorization logic.
  • app/Events/: Define your custom broadcast events.

Implementation Patterns

Core Workflows

1. Broadcasting Events

  • Server-Side:
    // Define an event
    class MessageSent implements ShouldBroadcast
    {
        public function broadcastOn(): array
        {
            return ['message-channel'];
        }
    
        public function broadcastAs(): string
        {
            return 'message.sent';
        }
    }
    
    // Broadcast the event
    broadcast(new MessageSent($data))->toOthers();
    
  • Client-Side:
    Echo.channel('message-channel')
        .listen('message.sent', (data) => {
            console.log('New message:', data);
        });
    

2. Channel Authorization

Use routes/channels.php to authorize channels:

Broadcast::channel('private-user.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

3. Presence Channels

Track users in a channel:

Broadcast::channel('chat.room.{id}', function ($user, $id) {
    return $user->canAccessRoom($id);
});

// Client-side
Echo.join(`chat.room.${roomId}`)
    .here((users) => console.log('Users here:', users))
    .joining((user) => console.log('User joined:', user))
    .leaving((user) => console.log('User left:', user));

4. Private Channels with Authentication

Use Laravel's auth middleware:

Broadcast::channel('private-app.{user}', function ($user) {
    return Auth::check();
});

5. Scaling with Multiple Servers

Configure Redis pub/sub for horizontal scaling:

REVERB_SCALE=true
REVERB_SCALE_CHANNEL=reverb-scale-channel

Integration Tips

Frontend Integration

  • Use Laravel Echo with Pusher JS or Socket.IO for client-side WebSocket management.
    import Echo from 'laravel-echo';
    import Pusher from 'pusher-js';
    
    window.Pusher = Pusher;
    window.Echo = new Echo({
        broadcaster: 'reverb',
        key: 'app_key',
        wsHost: window.location.hostname,
        wsPort: 6001,
        forceTLS: false,
        disableStats: true,
        enabledTransports: ['ws', 'wss'],
    });
    

Testing

  • Use Laravel's BroadcastServiceProvider and BroadcastFake for unit tests:
    use Illuminate\Support\Facades\Broadcast;
    
    public function test_broadcast_event()
    {
        Broadcast::fake();
    
        broadcast(new TestEvent())->to('test-channel');
    
        Broadcast::assertSent(TestEvent::class, function ($event) {
            return $event->data === 'test';
        });
    }
    

Monitoring and Logging

  • Configure Reverb logging in config/reverb.php:
    'log_level' => 'debug',
    'log_file' => storage_path('logs/reverb.log'),
    
  • Use Laravel's Log facade to debug connection issues:
    \Log::debug('WebSocket connection established', ['connection_id' => $connection->id]);
    

Customizing Reverb

  • Extend Reverb's behavior by binding custom classes in AppServiceProvider:
    public function register()
    {
        $this->app->bind(\Laravel\Reverb\Contracts\Connection::class, function () {
            return new \App\Services\CustomReverbConnection();
        });
    }
    

Gotchas and Tips

Pitfalls and Debugging

1. Connection Issues

  • Symptoms: Clients fail to connect or disconnect abruptly.
  • Causes:
    • Incorrect Redis configuration (e.g., wrong host/port).
    • Firewall blocking WebSocket ports (6001 by default).
    • Missing CORS headers (configure in config/reverb.php):
      'allowed_origins' => ['http://localhost', 'https://your-app.com'],
      
  • Fix:
    • Verify Redis is running and accessible:
      redis-cli ping
      
    • Check Reverb logs (storage/logs/reverb.log).
    • Ensure REVERB_HOST and REVERB_PORT match your frontend connection.

2. Authentication Failures

  • Symptoms: Clients connect but receive unauthorized errors.
  • Causes:
    • Missing or incorrect auth endpoint in Echo config.
    • Incorrect channel authorization logic in routes/channels.php.
  • Fix:
    • Ensure your BroadcastServiceProvider includes:
      Broadcast::routes(['middleware' => ['auth:sanctum']]);
      
    • Test auth with:
      php artisan reverb:auth
      

3. Memory Leaks

  • Symptoms: High memory usage or crashes under load.
  • Causes:
    • Unclosed WebSocket connections (fixed in v1.7.0).
    • Large channel lists or unoptimized event data.
  • Fix:
    • Use REVERB_ACTIVITY_TIMEOUT to prune idle connections:
      REVERB_ACTIVITY_TIMEOUT=30
      
    • Limit channel subscriptions per user.

4. Rate Limiting

  • Symptoms: Clients get 429 Too Many Requests errors.
  • Fix:
    • Enable rate limiting in config/reverb.php:
      'rate_limiting' => [
          'enabled' => true,
          'max_attempts' => 100,
          'decay_seconds' => 60,
      ],
      

5. Scaling Issues

  • Symptoms: Messages not delivered across multiple Reverb instances.
  • Causes:
    • Missing Redis pub/sub configuration.
    • Incorrect REVERB_SCALE_CHANNEL.
  • Fix:
    • Ensure all Reverb instances share the same Redis connection.
    • Verify scaling is enabled:
      REVERB_SCALE=true
      REVERB_SCALE_CHANNEL=reverb-scale-channel
      

Configuration Quirks

1. Custom Server Path

  • If Reverb is behind a reverse proxy (e.g., Nginx), set a custom path:
    REVERB_SERVER_PATH=/ws
    
  • Update Echo config:
    wsHost: window.location.hostname,
    wsPort: 6001,
    wsPath: '/ws',
    

2. HTTPS/SSL

  • For production, ensure Reverb uses WSS (secure WebSocket):
    REVERB_SCHEME=https
    
  • Configure your web server to proxy WebSocket connections:
    location /ws {
        proxy_pass http://127.0.0.1:6001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
    

3. Environment-Specific Config

  • Use Laravel's environment-specific configs:
    // config/reverb.php
    'host' => env('REVERB_HOST', '127.0.0.1'),
    'port' => env('REVERB_PORT', env('APP_ENV') === 'production' ? 443 :
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony