What am i missing? I did everything right but when i sent a new Event my console just doesnt log anything, here is my code:
FRONT END
I imported the required libraries:
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = Echo;
window.pusherEcho = new Echo({
broadcaster: 'pusher',
key: 'my-key',
cluster: 'us2',
forceTLS: true,
wsHost: window.location.host,
wsPort: 8000
});
BACK END
My event class:
<?php
namespace App\Events;
// ... imports
class ReceivedNotification implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('received-notification');
}
}
I registered a route just to test it:
Route::get('/event', function() {
event(new App\Events\ReceivedNotification('Hello world'));
return 'event sent';
});
FRONT END
I'm listening to events in some page with Laravel Echo:
pusherEcho.channel('received-notification')
.listen('ReceivedNotification', (e) => {
console.log(e);
});
When i go to the route /event
it never triggers the console.log
above, which means something is just wrong, yes my .env
file is everything ok i already checked:
BROADCAST_DRIVER=pusher
.
.
.
PUSHER_APP_ID=***
PUSHER_APP_KEY=***
PUSHER_APP_SECRET=***
PUSHER_APP_CLUSTER=us2
As we can see you are creating private channel in App\Events\ReceivedNotification and listen public channel in front-end. So change your front-end to below code :
pusherEcho.private('received-notification')
.listen('ReceivedNotification', (e) => {
console.log(e);
});
Also register your Event and Listerner in app\Providers\EventServiceProvider like :
protected $listen = [
'App\Events\ReceivedNotification' => [
'App\Listeners\ReceivedNotificationListener'
],
]