Real-time

/laravel-agent:broadcast:make

Create broadcast event with channel configuration

Overview

The /broadcast:make command generates a broadcast event with channel authorization for real-time communication. It creates event classes and configures channel authorization in your Laravel application, supporting public, private, and presence channels.

Usage

/laravel-agent:broadcast:make <EventName> [channel-type] [channel-name]

Examples

# Create a public channel broadcast event
/laravel-agent:broadcast:make OrderUpdated

# Create a private channel broadcast event
/laravel-agent:broadcast:make MessageSent private user.{id}

# Create a presence channel broadcast event
/laravel-agent:broadcast:make UserJoined presence chat.{roomId}

What Gets Created

A complete broadcast event includes the following components:

Component Location Description
Event Class app/Events/ Broadcast event with ShouldBroadcast interface
Channel Authorization routes/channels.php Authorization logic for private/presence channels

Channel Types

Laravel supports three types of broadcast channels:

Public Channels

Anyone can listen to public channels without authentication:

/laravel-agent:broadcast:make OrderUpdated

Private Channels

Require authorization for users to listen. Use for user-specific data:

/laravel-agent:broadcast:make MessageSent private user.{id}

Presence Channels

Like private channels but also track who is subscribed. Perfect for chat rooms:

/laravel-agent:broadcast:make UserJoined presence chat.{roomId}

Generated Event Example

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MessageSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public string $message,
        public int $userId
    ) {}

    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('user.' . $this->userId),
        ];
    }

    public function broadcastAs(): string
    {
        return 'message.sent';
    }
}

Usage Examples

Broadcasting Events

<?php

// Dispatch event to all listeners
broadcast(new MessageSent($message, $userId));

// Exclude the current user (sender)
broadcast(new MessageSent($message, $userId))->toOthers();

Listening on the Client

// Public channel
Echo.channel('orders')
    .listen('.order-updated', (e) => {
        console.log(e);
    });

// Private channel
Echo.private('user.' + userId)
    .listen('.message-sent', (e) => {
        console.log(e.message);
    });

// Presence channel
Echo.join('chat.' + roomId)
    .here((users) => {
        console.log('Users in room:', users);
    })
    .joining((user) => {
        console.log(user.name + ' joined');
    })
    .leaving((user) => {
        console.log(user.name + ' left');
    })
    .listen('.user-joined', (e) => {
        console.log(e);
    });

Channel Authorization

For private and presence channels, authorization is automatically added to routes/channels.php:

<?php

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

// Presence channel authorization with user data
Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
    if ($user->canAccessRoom($roomId)) {
        return [
            'id' => $user->id,
            'name' => $user->name,
            'avatar' => $user->avatar_url,
        ];
    }
});

Process Flow

  1. Parse Arguments - Extract event name, channel type (public/private/presence), and channel name pattern
  2. Invoke Reverb Agent - Use the Reverb agent to generate the broadcast event and channel configuration
  3. Create Event Class - Generate the event class in app/Events/ with the ShouldBroadcast interface
  4. Configure Authorization - Add channel authorization to routes/channels.php for private/presence channels
  5. Report Results - Display created files and usage examples

Best Practices

  1. Queue events - Use ShouldBroadcastNow for immediate broadcast or implement ShouldQueue for queued broadcasting
  2. Secure private channels - Always verify user authorization in channel callbacks
  3. Minimize payload - Only broadcast essential data; fetch additional data on the client if needed
  4. Use presence channels wisely - Great for chat/collaboration, but they maintain WebSocket connections per user
  5. Test authorization - Ensure your channel authorization logic prevents unauthorized access

Related Agent

This command uses the Reverb agent for broadcast event creation and channel configuration.

See Also