Laravel Echo and broadcasting from a package

While implementing Laravel Echo for a package I found an small problem. By default Laravel Echo looks in App\Events for events, and therefor I could not listen to the event \MyCompoany\Reservations\Event\ReservationChanged from the frontend.


// ReservationController.php

use MyCompoany\Reservations\Events\ReservationChanged;

...

broadcast(new ReservationChanged($reservation))->toOthers();

Laravel Echo listen() need the full namespace to listen to the events.

There are two solutions to this problem:

  1. Use dot-notation like this, but this can get a bit cumbersome.

// bootstrap.js

    .listen('.MyCompany.Reservations.Event.ReservationChanged', ({ reservation }) => {
        console.log(reservation);
    });


2. Set namespace directly on Echo upon creation:

// bootstrap.js

import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');

window.Echo = new Echo({
     broadcaster: 'pusher',
     key: 'xxxxxxxxxxxxxx',
     cluster: 'eu',
     encrypted: true,
     namespace: 'MyCompoany.Reservations.Events', // Set the namespace here
});

Then you can listen for events as usual.

window.Echo.private('reservation.' + teamId)
    .listen('ReservationChanged', ({ reservation }) => {
        console.log(reservation);
    });