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.
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.
Pusher Channels acts as a realtime layer between your client and server events, maintaining persistent connections to the clients.
laravel-echo - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers.
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
})
})
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With