Laravel - Broadcasting - Only To Others

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:

    
    use App\Events\OrderShipmentStatusUpdated;
    
    broadcast(new OrderShipmentStatusUpdated($update))->toOthers();
	

To better understand when you may want to use the toOthers method, let's imagine a task list application where a user may create a new task by entering a task name. To create a task, your application might make a request to a /task URL which broadcasts the task's creation and returns a JSON representation of the new task. When your JavaScript application receives the response from the end-point, it might directly insert the new task into its task list like so:

    
    axios.post('/task', task)
        .then((response) => {
            this.tasks.push(response.data);
        });
	

However, remember that we also broadcast the task's creation. If your JavaScript application is also listening for this event in order to add tasks to the task list, you will have duplicate tasks in your list: one from the end-point and one from the broadcast. You may solve this by using the toOthers method to instruct the broadcaster to not broadcast the event to the current user.

Your event must use the Illuminate\Broadcasting\InteractsWithSockets trait in order to call the toOthers method.