How do I pass a variable to JavaScript using Laravel in order to broadcast on a private channel?

157 Views Asked by At

I am building an app in Laravel 9.42.2 and have set up Laravel Echo and Soketi to broadcast events. I can successfully send and receive broadcasts on public channels, but I can't figure out how to broadcast on a private channel.

According to the docs I can do this with the example code below:

Echo.private(`orders.${orderId}`)
    .listen('OrderShipmentStatusUpdated', (e) => {
        console.log(e.order);
    });

What I don't understand is where the ${orderId} is passed to the JavaScript. I can create the private channel on the backend in PHP, but I don't know where the front end should be receiving the variables it needs to fill in the placeholders in the listener.

Options I have considered:

  • Query the database at the front of every response and send a list of all possible ID's back to the user to store for use as needed (i.e. get all orderId's related to the user as an array and use a loop to create a listener for each of them). I'm concerned this would add a lot of unnecessary trips to the database and overhead to the page load times for something that might not be needed.
  • Add a line in the Controller to parse the orderId to json just before calling the event dispatch. Not sure why this feels wrong, but it does.
1

There are 1 best solutions below

0
NIKUNJ PATEL On

You can do via this tricks.

The orderId can be a part of your page url or can be represented by a hidden element in your template, for example:

<input type="hidden" id="orderId" value="{{$orderId}}" />

In case you choose hidden element, just get its value and pass to the Echo.private() method.

var orderId = document.getElementById('orderId').value;
window.Echo.private(`orders.` + orderId)
    .listen('OrderShipmentStatusUpdated', (e) => {
        console.log(e);
});