Search code examples
laravelwebsocketlaravel-echo

Why use Laravel's broadcast "toOthers" vs update everyone on broadcast (including self)?


Laravel's broadcast toOthers method is used to exclude the current user from the broadcast's recipients. The official documentation includes an example of adding a task to a list via Javascript w/ an end-point, then broadcasting the addition out to update other users.

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

...

Echo.channel('orders')
.listen('TaskCreated', (e) => {
    this.tasks.push(e.task);
});

If the user who created the task receives the broadcast, it would add a duplicate task to their list. So the toOthers method is used within the TaskController:

broadcast(new TaskCreated($task))->toOthers();

I've seen similar task list examples used in various Laravel Echo tutorials/videos/articles, and they all use this pattern - but I don't understand why.

Given this example, what's the reason we don't simply update the current user's task list exclusively from the broadcast along with everyone else?

Why do we duplicate code to push from both the axios response and broadcast listener, which then requires the use of toOthers?

(I understand that it's not a big deal either way w/ this example. It seems important though when dealing with more complex response handling and many different listeners.)


Solution

  • Using the toOthers means less data usage and faster responses on current user. For example if your broadcast task is queued and the queue is backed up, your current user will still see the changes immediately.