Ligonsker's avatar

How to make use of Laravel's broadcasting 2-way connection (websocket) capability to send data instead of using Ajax/sendBeacon?

I have a Laravel-Websockets server running and broadcasting events. In the frontend, I get real-time updates with Laravel Echo, so everything works well.

One of the things I do right now is to send data on certain events with Ajax or Beacon, for example, letting other users know when certain user is moving or stopped moving his mouse:

    function mouseMoving() {
        isMouseMoving = true;
        navigator.sendBeacon("/mouse-moving");    
    }
    
    function mouseStopped() {
        isMouseMoving = false;
        navigator.sendBeacon("/mouse-stopped-moving");    
    }
    
    window.addEventListener("mousemove",function(){
        if (!isMouseMoving) {
            mouseMoving();
        }
        
        clearTimeout(timer);
        timer = setTimeout(mouseStopped,300);
    });

Then, in the backend (In the controller), I need to get the user's details and broadcast to others. So because I needed to get the user's details via the Auth details, I didn't want to broadcast it directly from client to client as seen here: https://laravel.com/docs/10.x/broadcasting#client-events

Instead, I wanted the event to go to the server first, get the information needed and then be broadcast. But it looks odd to me that I am using Ajax / sendBeacon if there is already an open two-way connection between the server and the client.

Can I call the endpoints (/mouse-stopped-moving and /mouse-moving) while taking advantage of the websocket connection? Or what I do is still the correct way?

0 likes
0 replies

Please or to participate in this conversation.