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

Laravel Websocket Laravel Package

bugover/laravel-websocket

Fork of beyondcode/laravel-websockets bringing WebSockets to Laravel as a drop-in Pusher replacement. Supports SSL, Laravel Echo, and a debug dashboard, plus added connection events and two-way client-to-server messaging.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bugover/laravel-websocket
    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
    php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
    php artisan migrate
    
  2. Configure Broadcasting: Update config/broadcasting.php:

    'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'host' => env('PUSHER_HOST', '127.0.0.1'),
            'port' => env('PUSHER_PORT', 6001),
            'scheme' => env('PUSHER_SCHEME', 'http'),
            'encrypted' => true,
            'useTLS' => env('PUSHER_SCHEME') === 'https',
        ],
    ],
    
  3. Start Server:

    php artisan websockets:serve
    
  4. Test Connection: Use Laravel Echo in your frontend:

    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: process.env.MIX_PUSHER_APP_KEY,
        wsHost: window.location.hostname,
        wsPort: 6001,
        forceTLS: false,
        disableStats: true,
    });
    

First Use Case: Real-Time Notifications

  1. Publish an Event:

    // In your controller or command
    event(new NotificationSent($userId, $message));
    
  2. Listen in Frontend:

    Echo.channel(`user.${userId}`)
        .listen('NotificationSent', (data) => {
            console.log('New notification:', data);
        });
    

Implementation Patterns

Core Workflows

1. Broadcasting Events

  • Laravel Facade:
    // Publish an event to all listeners
    broadcast(new App\Events\ChatMessage($message))->toOthers();
    
    // Or via facade
    event(new App\Events\ChatMessage($message));
    
  • Channel Targeting:
    // Private channel (authenticated users)
    broadcast(new ChatMessage($message))->to($user);
    
    // Presence channel (track online users)
    broadcast(new UserOnline($user))->toOthers();
    

2. Two-Way Messaging (Client ↔ Server)

  • Client-Side:
    // Send data to server
    const socket = new WebSocket(`ws://${window.location.hostname}:6001/app/${appId}`);
    socket.onopen = () => socket.send(JSON.stringify({ event: 'customEvent', data: { key: 'value' } }));
    
  • Server-Side Handling: Extend BaseController:
    namespace App\Http\Controllers;
    
    use BeyondCode\LaravelWebSockets\Contracts\WebSocketController;
    
    class CustomWebSocketController extends BaseController implements WebSocketController
    {
        public function onMessage($connection, $message)
        {
            $data = json_decode($message, true);
            if ($data['event'] === 'customEvent') {
                // Process data and broadcast response
                broadcast(new CustomResponse($data['data']))->to($connection);
            }
        }
    }
    
    Register in websockets.php:
    'controllers' => [
        'App\Http\Controllers\CustomWebSocketController',
    ],
    

3. Connection Events

  • Listen for Connections:
    use BeyondCode\LaravelWebSockets\Events\Connections\ConnectionConnected;
    use BeyondCode\LaravelWebSockets\Events\Connections\ConnectionDisconnected;
    
    // In EventServiceProvider
    protected $listen = [
        ConnectionConnected::class => [
            'App\Listeners\LogConnection',
        ],
        ConnectionDisconnected::class => [
            'App\Listeners\LogDisconnection',
        ],
    ];
    

4. Multi-Tenancy

  • Configure apps in websockets.php:
    'apps' => [
        [
            'id' => 'myapp',
            'name' => 'My App',
            'key' => 'app_key',
            'secret' => 'app_secret',
            'capacity' => 1000,
            'enable_client_messages' => true,
        ],
    ],
    

Integration Tips

Laravel Echo

  • Auto-Discovery: Echo automatically detects Pusher config in broadcasting.php.
  • Custom Host/Port:
    Echo.connector.pusher.config.host = 'your-websocket-domain';
    Echo.connector.pusher.config.port = 6001;
    

Debugging

  • Dashboard: Access at /laravel-websockets (enable in websockets.php).
  • Logs: Check storage/logs/laravel-websocket.log for server-side issues.

Scaling

  • Redis Channel Manager:
    'channel_manager' => 'redis',
    'redis' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'port' => env('REDIS_PORT', 6379),
        'password' => env('REDIS_PASSWORD', null),
    ],
    
  • Event Loop: Install pecl install ev for >1024 connections.

SSL/TLS

  • Generate certificates:
    openssl req -x509 -newkey rsa:4096 -keyout local_cert.key -out local_cert.pem -days 365 -nodes
    
  • Configure in websockets.php:
    'ssl' => [
        'local_cert' => storage_path('app/ssl/local_cert.pem'),
        'local_pk' => storage_path('app/ssl/local_cert.key'),
        'passphrase' => null,
    ],
    

Gotchas and Tips

Pitfalls

  1. Connection Limits:

    • Default stream_select event loop caps at 1,024 connections. Symptoms: Dropped connections or timeouts.
    • Fix: Install pecl install ev and set event_loop=ev in websockets.php.
  2. CORS Issues:

    • Browser blocks WebSocket connections if allowed_origins in websockets.php is misconfigured.
    • Fix: Set allowed_origins to your frontend domain(s):
      'allowed_origins' => [
          'https://your-app.com',
          'http://localhost:3000',
      ],
      
  3. Missing Pusher Credentials:

    • Laravel Echo requires PUSHER_APP_ID, PUSHER_APP_KEY, PUSHER_APP_SECRET in .env.
    • Fix: Generate dummy values or reuse existing Pusher keys (no API calls needed).
  4. Database Stats Overhead:

    • Enabling enable_statistics adds ~10ms latency per connection. Disable in production if unused:
      'enable_statistics' => env('APP_ENV') !== 'production',
      
  5. Channel Manager Mismatch:

    • Using ArrayChannelManager in production with high channel counts (>10K) causes memory leaks.
    • Fix: Switch to Redis:
      'channel_manager' => 'redis',
      
  6. Two-Way Messaging Not Working:

    • Ensure enable_client_messages is true for the app and the controller implements WebSocketController.
    • Debug: Check storage/logs/laravel-websocket.log for unhandled messages.
  7. SSL Errors:

    • Self-signed certificates trigger browser warnings. Use Let’s Encrypt or a trusted CA in production.
    • Fix: Configure Nginx as a reverse proxy for TLS termination:
      location / {
          proxy_pass http://127.0.0.1:6001;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
      }
      

Debugging Tips

  1. Check Connection Status:

    curl -N http://localhost:6001/apps/{app_id}/channels/private-test-channel
    
    • 200 OK: Connection active.
    • 403 Forbidden: Auth or CORS issue.
  2. Monitor Processes:

    ps aux | grep websockets
    
    • Ensure no zombie processes (capacity exceeded).
  3. Log Levels: Adjust in websockets.php:

    'log_level' => 'debug', // 'debug', 'info', 'warning', 'error'
    
  4. Simulate High Load: Use websockets:load-test:

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity