I am working on a chat/message feature for an app. When a User sends a message, I want a specific Event to be triggered and to be broadcasted. I am then wanting Laravel Echo to listen on the event's broadcast channel to an event via Laravel Echo, using the pusher
driver.
I am wanting the Laravel Echo implementation to be in a Vue component and to retrieve the data that was broadcasted via the event. Currently, I can't get an event to broadcast to either a private channel or just a channel.
Here is what I have done:
1) Added the config to .env
.
2) Added config to bootstrap.js
:
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'mykey',
encypted: false
});
3) Added auth check in App\Providers\BroadcastServiceProvider
(just returning true if User is signed in for now):
Broadcast::channel('chat', function ($user) {
// verify that user is recipient of message
return \Auth::check();
});
4) Added App\Providers\BroadcastServiceProvider::class,
to App/config/app.php
.
5) Created the Event App\Events\UserSentMessage
, which broadcasts on a PrivateChannel
named chat
. I have also tried to broadcast to a Channel
. I checked and the event is being fired from a call to the event()
helper in a controller, it just seems to not be broadcast. I have also tried using the broadcast
method in the controller mentioned.
6) Added the following within the mounted
Vue life cycle hook in a valid Vue component (component is rendering data etc as expected, just not working with Laravel Echo atm):
Echo.private('chat').listen('UserSentMessage', (data) => {
console.log(data);
}, (e) => {
console.log(e);
});
Have also tried:
Echo.channel('chat').listen('UserSentMessage', (data) => {
console.log(data);
}, (e) => {
console.log(e);
});
The Vue component is successfully subscribing to the channel specified. The pusher debug console recognized that it is being subscribed to, but the Event, when triggered never gets broadcasted.
Seems to be that there is a problem with broadcasting the event. I have also tried using the broadcast()
helper, rather than the event()
helper.
Also, when subscribing to the event with Laravel Echo via Echo.private()
. It seems to prefix the channel name with private
, so I have also tried broadcasting (in the event) to a channel named private-chat
.
I can recommend You to check Your .env
file
and make sure BROADCAST_DRIVER
is not log
(try pusher
)
and also don't forget to keep running queue listener:
php artisan queue:listen
UPD.: if You look for more advanced solution, read about laravel horizon