Backend Usage

Using event for broadcast message

Laravel Events provide a great interface to send data in the socket messages.

php artisan make:event EventName

You don't want your users to have to refresh the page to view status updates. Instead, you want to broadcast the updates to the application as they are created. So, you need to mark the event with the ShouldBroadcast interface. This will instruct Laravel to broadcast the event when it is fired.

The ShouldBroadcast interface requires our event to define a broadcastOn method. This method is responsible for returning the channels that the event should broadcast on. An empty stub of this method is already defined on generated event classes, so we only need to fill in its details.

The ShouldBroadcast interface requires you to implement a single method: broadcastOn. The broadcastOn method should return a channel or array of channels that the event should broadcast on. The channels should be instances of Channel, PrivateChannel, or PresenceChannel. Instances of Channel represent public channels that any user may subscribe to, while PrivateChannels and PresenceChannels represent private channels that require channel authorization.

When an event is broadcast, all of its public properties are automatically serialized and broadcast as the event's payload, allowing you to access any of its public data from your JavaScript application. However, if you wish to have more fine-grained control over your broadcast payload, you may add a broadcastWith method to your event. This method should return the array of data that you wish to broadcast as the event payload.

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

    /**
    * @var Message
    */
    private $message;

    /**
    * Create a new event instance.
    *
    * @return void
    */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    /**
    * Get the channels the event should broadcast on.
    *
    * @return \Illuminate\Broadcasting\Channel|array
    */
    public function broadcastOn()
    {
        return new Channel('channelName');
    }

    /**
    * JSON data to broadcast with this message
    */
    public function broadcastWith()
    {
        return $this->message->toArray();
    }
}}

There is just one last task before your backend gets ready. Events are broadcast over "channels", which may be specified as public or private. Any visitor to your application may subscribe to a public channel without any authentication or authorization; however, in order to subscribe to a private channel, a user must be authenticated and authorized to listen on that channel. You need to secure your channel. The users must be authorized to listen on private channels. We may define our channel authorization rules in our application's routes/channels.php file.

The channel method accepts two arguments: the name of the channel and a callback which returns true or false indicating whether the user is authorized to listen on the channel. All authorization callbacks receive the currently authenticated user as their first argument and any additional wildcard parameters as their subsequent arguments.

Broadcast::channel('channelName', function ($user) {
    return true,
});

Once you have defined an event and marked it with the ShouldBroadcast interface, you only need to fire the event and queue the event for broadcasting.

broadcast(new MessageSentEvent($message));

When building an application that utilizes event broadcasting, you may occasionally need to broadcast an event to all subscribers to a given channel except for the current user. You may accomplish this using the broadcast helper and the toOthers method.

broadcast(new MessageSentEvent($message))->toOthers();

Last updated