Summer sale! Save 50% on access to our entire library of courses.Join here →

How to fix toOthers when broadcasting with a Laravel API request

July 12th, 2024

The toOthers method won't work correctly if you're triggering a broadcast via an API request to your Laravel application. Here's why and how to fix it.

If you're sending an Ajax request to your Laravel application and broadcasting, using toOthers can't pick up the Socket ID of the connected client, and you'll need to manually send it along with your request for it to work.

When you use toOthers, deep down in the Laravel codebase, it'll invoke a dontBroadcastToCurrentUser method:

public function dontBroadcastToCurrentUser()
{
    $this->socket = Broadcast::socket();

    return $this;
}

The Broadcast::socket() method looks like this, and you'll probably immediately spot the problem.

public function socket($request = null)
{
    if (! $request && ! $this->app->bound('request')) {
        return;
    }

    $request = $request ?: $this->app['request'];

    return $request->header('X-Socket-ID');
}

The last line expects an X-Socket-ID header, which is sent by default when we make a request to Laravel, but not for Ajax requests.

Laravel requires an X-Socket-ID header to exclude the current user from broadcasts, so let's fetch it and pass it down with our requests.

The Socket ID is assigned after you connect to a channel with Laravel Echo:

const channel = Echo.join(`someRoom`)

console.log(Echo.socketId())

You'll get back the Socket ID using the socketId method from Laravel Echo.

For any requests you make to your backend via Ajax, all you need to do is pass down the X-Socket-ID header we saw in the last section of this article:

axios.post(`/some/endpoint`, payload, {
    headers: {
        'X-Socket-Id': Echo.socketId()
    }
})

Now that you're sending the header down, Laravel can identify the current user's Socket ID and exclude it from the list of clients to broadcast to.

You can also set this as a default using Axios to always be sent down, but this needs to be set after you've connected to the channel with Echo, since that's when a Socket ID gets assigned.

const channel = Echo.join(`someRoom`)

window.axios.defaults.headers.common['X-Socket-Id'] = Echo.socketId()

Once you've set this, all subsequent network requests will contain the X-Socket-Id header to identify the client initiating the broadcast via the Ajax request.

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.