I'm trying to detect when client is disconnected from websocket and trigger some function with it, but so far I had no success.
I'm using BeyondCode websockets and the way I'm calling class is like:
Broadcast::channel('order.{id}', OrderChannel::class);
So this OrderChannel class has function
public function join(User $user, Orders $id)
{
return ['id' => $user->id, 'name' => $user->name, 'image' => $user->profile_photo];
}
and it's working as expected, but I would like to update something in database when user disconnect from that socket, and I tried something like:
public function leave(User $user, Orders $id)
{
$order = Orders::where('id', $id)->withTrashed()->update(['user_id' => null]);
return $order;
}
But it's not working, any suggestions how to trigger this?
My Answer:
You can use the `onClose` event in your frontend code to detect when the client is disconnected from the websocket. Here's an example using Vue.js:
javascript
export default {
mounted() {
Echo.channel('order.' + this.orderId)
.listen('.OrderEvent', (e) => {
console.log('Event received:', e);
})
.onClose(() => {
console.log('Socket connection closed');
// Call your function to update something in the database here
});
},
}
In this example, we are listening for events on the `order.{id}` channel and logging them to the console. When the socket connection is closed, the `onClose` callback is triggered where you can call your function to update the database.
Make sure to replace `this.orderId` with the actual order ID in your Vue component.
Additionally, make sure that your Laravel backend is properly handling the disconnection event. You may need to adjust your `leave` function in the `OrderChannel` class to properly update the database when a user disconnects.
Rate this post
3 of 5 based on 1897 votesComments