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, enabling broadcasting and live updates with a first-party, self-hosted server and seamless Laravel integration. Ideal for chat, notifications, and presence features.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/reverb
    php artisan reverb:install
    

    This publishes the config, creates a Redis pub/sub connection, and sets up the WebSocket server.

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

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

    use Illuminate\Support\Facades\Broadcast;
    
    Broadcast::channel('chat', function ($user) {
        return ['id' => $user->id];
    });
    
    // In a controller or event
    Broadcast::to('chat')->send('New message!');
    
  4. Client-Side Connection: Connect using JavaScript with the Reverb server:

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

Implementation Patterns

Core Workflows

  1. Channel Management:

    • Dynamic Channels: Use closures to dynamically resolve channels:
      Broadcast::channel('user.{user}', function ($user) {
          return ['id' => $user->id];
      });
      
    • Presence Channels: Track online users with Broadcast::presenceChannel():
      Broadcast::presenceChannel('chat', function ($user, $room) {
          return ['user_id' => $user->id, 'room_id' => $room->id];
      });
      
  2. Event Broadcasting:

    • Broadcasting Events:
      class NewMessage implements ShouldBroadcast
      {
          public $message;
      
          public function __construct($message)
          {
              $this->message = $message;
          }
      
          public function broadcastOn()
          {
              return new Channel('chat');
          }
      }
      
    • Private Events: Use broadcastAs() for private channels:
      public function broadcastAs()
      {
          return 'private-message';
      }
      
  3. Authentication:

    • Token-Based Auth: Use Broadcast::auth() in channels:
      Broadcast::channel('private-chat.{user}', function ($user) {
          return ['id' => $user->id];
      }, function ($user, $options) {
          return $user->api_token === $options['token'];
      });
      
    • Client-Side Auth: Pass tokens via WebSocket query params:
      const socket = new WebSocket(`ws://${window.location.hostname}:6001?token=${userToken}`);
      
  4. Scaling and Load Balancing:

    • Redis Pub/Sub: Reverb uses Redis for pub/sub, ensuring horizontal scalability.
    • Connection Limits: Configure per-app limits in config/reverb.php:
      'connection_limits' => [
          'max_connections' => 1000,
          'max_connections_per_ip' => 100,
      ],
      
  5. Rate Limiting:

    • Enable rate limiting in config/reverb.php:
      'rate_limiting' => [
          'enabled' => true,
          'max_attempts' => 100,
          'decay_seconds' => 60,
      ],
      
  6. Pusher Compatibility:

    • HTTP API: Reverb supports Pusher’s HTTP API for auth and events:
      // In routes/web.php
      Route::post('/pusher/auth', [PusherAuthController::class, 'auth']);
      
    • Signature Verification: Ensure APP_KEY and APP_ENV are set correctly for Pusher compatibility.

Integration Tips

  1. Laravel Echo: Configure Echo to use Reverb:

    import Echo from 'laravel-echo';
    
    window.Pusher = require('pusher-js');
    
    window.Echo = new Echo({
        broadcaster: 'reverb',
        key: process.env.MIX_PUSHER_APP_KEY,
        wsHost: window.location.hostname,
        wsPort: 6001,
        forceTLS: false,
        disableStats: true,
    });
    
  2. Testing:

    • Use ReverbTestCase for WebSocket tests:
      use Laravel\Reverb\Testing\ReverbTestCase;
      
      class ChatTest extends ReverbTestCase
      {
          public function test_broadcasting()
          {
              $this->broadcastingTo('chat')
                   ->then(function ($event) {
                       $this->assertEquals('Hello!', $event['message']);
                   });
      
              Broadcast::to('chat')->send('Hello!');
          }
      }
      
  3. Custom Middleware: Extend Reverb’s middleware for custom logic:

    namespace App\Broadcasting;
    
    use Laravel\Reverb\Middleware\Authenticate;
    
    class CustomAuthenticate extends Authenticate
    {
        public function handle($request, Closure $next)
        {
            // Custom auth logic
            return $next($request);
        }
    }
    

    Register in config/reverb.php:

    'middleware' => [
        \App\Broadcasting\CustomAuthenticate::class,
    ],
    
  4. Monitoring:

    • Use Redis CLI to monitor pub/sub:
      redis-cli monitor
      
    • Log WebSocket connections in app/Providers/ReverbServiceProvider.php:
      Reverb::connection()->on('connecting', function ($connection) {
          Log::info('New connection', ['socket_id' => $connection->id]);
      });
      

Gotchas and Tips

Pitfalls

  1. Redis Connection Issues:

    • Symptom: WebSocket connections drop or fail to connect.
    • Fix: Ensure Redis is running and accessible. Check REVERB_REDIS_URL in .env:
      REVERB_REDIS_URL=redis://user:pass@127.0.0.1:6379/0
      
    • Debug: Use redis-cli ping to verify Redis connectivity.
  2. CORS Errors:

    • Symptom: Browser blocks WebSocket connections due to CORS.
    • Fix: Configure allowed origins in config/reverb.php:
      'allowed_origins' => [
          'http://localhost:3000',
          'https://your-app.com',
      ],
      
    • Wildcard Support: Use * for development (not production):
      'allowed_origins' => ['*'],
      
  3. Memory Leaks:

    • Symptom: High memory usage or crashes under load.
    • Fix: Ensure activity_timeout is set in config/reverb.php:
      'activity_timeout' => 60, // seconds
      
    • Monitor: Use php artisan reverb:stats to check active connections.
  4. Event Data Serialization:

    • Symptom: Events with complex data (e.g., objects, resources) fail to broadcast.
    • Fix: Ensure data is JSON-serializable or use broadcastWith():
      public function broadcastWith()
      {
          return ['message' => $this->message, 'user' => $this->user->toArray()];
      }
      
  5. Pusher HTTP API Mismatches:

    • Symptom: Pusher HTTP API requests fail with signature errors.
    • Fix: Verify APP_KEY and APP_ENV match between Reverb and your app:
      // In PusherAuthController
      public function auth()
      {
          return Broadcast::auth(config('broadcasting.connections.reverb'));
      }
      
  6. Channel Data Validation:

    • Symptom: Presence channel events don’t update correctly.
    • Fix: Ensure channel data matches the expected format:
      // Correct format for presence channels
      Broadcast::presenceChannel('chat', function ($user, $room) {
          return [
              'user_id' => $user->id,
              'room_id' => $room->id,
              'data' => ['custom' => 'value'], // Optional
          ];
      });
      

Debugging Tips

  1. Logging: Enable debug logging in config/reverb.php:

    'log_level' => 'debug',
    

    View logs with:

    tail -f storage/logs/laravel.log
    
  2. WebSocket Debugging:

    • Use browser DevTools (Network tab) to inspect WebSocket traffic.
    • For raw debugging, use tcpdump or Wireshark to capture WebSocket frames:
      tcpdump -i any port 6001 -w reverb.pcap
      
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai