Composables

useEcho

Composable for working with Echo instance in your code.

Usage

By using this composable you can access the global object provided by the plugin and call any method to work with sockets on your backend.

For more details about the Echo instance and available functions, check official Laravel Broadcasting documentation.

Code sample

Here is an example of a client component subscribing to the public and private channels:

components/Broadcast.client.vue
<script setup lang="ts">
const echo = useEcho()

const messages = ref<string[]>([])
const writeNewMessage = (e: object) => messages.value.push(JSON.stringify(e))

function stopAllListeners() {
  echo.leaveAllChannels()
}

function subscribeToPublicChannel() {
  const name = 'public'
  const event = '.PublicEvent'

  echo
    .channel(name)
    .listen(event, (e: object) => writeNewMessage(e))
    .error((e: object) => {
      console.error('Public channel error', e)
    })
}

function subscribeToPrivateChannel() {
  const name = 'users'
  const event = '.PrivateEvent'

  echo
    .private(name)
    .listen(event, (e: object) => writeNewMessage(e))
    .error((e: object) => {
      console.error('Private channel error', e)
    })
}

onMounted(() => {
  subscribeToPublicChannel()
  subscribeToPrivateChannel()
})
</script>
Keep in mind, for accessing Private and Presence channels you should have configured authentication on your backend side, preferably Laravel Sanctum.