Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel echo: is it possible to listen to all events instead of a specific one?

I have implemented Laravel Broadcasting in my project. Everything is working fine but I'm wondering if it's possible to listen to all events instead of just a specific one?

Currently I have this code on my front-end:

window.Echo.channel('office-dashboard')
  .listen('CompanyUpdated', (e) => {
    console.log(e.company);
  });
  .listen('CompanyDeleted', (e) => {
    console.log(e.company);
  });

I want to structure my event in such a way that I can grab what kind of event it exactly was, and what kind of action was performed. But that's useless if I still have to listen to each event specifically, like I do now. I want to listen to all events in a channel, is that possible?

I read the docs, but those only talk about how to listen to a specific event.

like image 679
Snackoverflow Avatar asked Oct 06 '17 11:10

Snackoverflow


People also ask

What does echo do in laravel?

Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by your server-side broadcasting driver. You may install Echo via the NPM package manager.

What is pusher in laravel?

Pusher Channels acts as a realtime layer between your client and server events, maintaining persistent connections to the clients.

Is laravel echo free?

laravel-echo - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers.


2 Answers

I came across the same situation. I think you need to listen to individual channels. but you can write the code a bit cleaner like below.

    const channel = window.Echo.channel('office-dashboard')

    const eventsTolisten = [
      'CompanyUpdated',
      'CompanyDeleted',
    ]

    eventsTolisten.forEach(event => {
      channel.listen(event, e => {
        this.handleSocketEvents({
          name: event,
          data: e.data
        })
      })
    })
like image 126
Rameez Rami Avatar answered Oct 10 '22 15:10

Rameez Rami


If you are using pusher as your broadcast driver, you have access to a listenToAll() method from your Laravel Echo instance. In short, you may do the following to listen for all events on a specific channel:

Echo.private(`office-dashboard`)
   .listenToAll((event, data) => {
      // do what you need to do based on the event name and data
      console.log(event, data)
   });

The listenToAll() method just takes a single argument, a callback, which will receive the name of the event as the first parameter and any data associated with the event as a second parameter.

like image 37
Denis Priebe Avatar answered Oct 10 '22 13:10

Denis Priebe