Laravel - Broadcasting - Model Broadcasting

Before reading the following documentation about model broadcasting, we recommend you become familiar with the general concepts of Laravel's model broadcasting services as well as how to manually create and listen to broadcast events.

It is common to broadcast events when your application's Eloquent models are created, updated, or deleted. Of course, this can easily be accomplished by manually defining custom events for Eloquent model state changes and marking those events with the ShouldBroadcast interface.

However, if you are not using these events for any other purposes in your application, it can be cumbersome to create event classes for the sole purpose of broadcasting them. To remedy this, Laravel allows you to indicate that an Eloquent model should automatically broadcast its state changes.

To get started, your Eloquent model should use the Illuminate\Database\Eloquent\BroadcastsEvents trait. In addition, the model should define a broadcastsOn method, which will return an array of channels that the model's events should broadcast on:

    
    belongsTo(User::class);
        }
    
        /**
         * Get the channels that model events should broadcast on.
         *
         * @param  string  $event
         * @return \Illuminate\Broadcasting\Channel|array
         */
        public function broadcastOn($event)
        {
            return [$this, $this->user];
        }
    }
	

Once your model includes this trait and defines its broadcast channels, it will begin automatically broadcasting events when a model instance is created, updated, deleted, trashed, or restored.

In addition, you may have noticed that the broadcastOn method receives a string $event argument. This argument contains the type of event that has occurred on the model and will have a value of created, updated, deleted, trashed, or restored. By inspecting the value of this variable, you may determine which channels (if any) the model should broadcast to for a particular event:

    
    /**
     * Get the channels that model events should broadcast on.
     *
     * @param  string  $event
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn($event)
    {
        return match($event) {
            'deleted' => [],
            default => [$this, $this->user],
        };
    }