javascriptlaravel-echo

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.


Solution

  • 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.