How to create private channel name dynamically

925 views Asked by At

I woluld like to create real-time order tracking system using laravel, vue and pusher. In admin panel I have list of all orders. The idea is when admin change order status the user (owner of this order) will get notification without refreshing page. To make it I want to use private channels. My problem is to create private channel name dynamically.

Admin panel looks like below.

<h1>Admin</h1>
<table>
    @foreach ($orders as $o)
    <tr>
        <td>{{$o->name}}</td>
        <td>{{$o->status}}</td>
        <td>{{$o->getUser->name}}</td>
        <td>
            <update-order-status :id="{{$o->id}}"></update-order-status>
        </td>
    </tr>
    @endforeach
</table>

There is update-order-status component which is a form used to change status of order. Id of order is passed to component via props. Content of component look like below:

///update-order-status component
<template>
  <div>
    <form method="GET" action="change_status">
      <input type="hidden" name="id" :value=id />
      <select name="status">
              <option value="placed">Placed</option>
               <option value="progres">Progres</option>
               <option value="delivered">Delivered</option>
            </select>
      <input type="submit" value="update status" v-on:click="upd(id)" />
    </form>
  </div>
</template>

<script>
  export default {
    created() {
    },
    props: ["id"],

    data: function() {
      return {


      };
    },

    methods: {
      upd: function(id) {
        this.$root.$emit("eve", id);
      }
    }
  };
</script>

When admin submit form order status is updated in database and also event eve is emitted. This event is used to pass id of order to status-changed compoennt. This component is placed in user panel and contains notification that order status has been changed.

///status changed component

<template>
 <div  v-if="sn" class="notification is-primary">
  <button class="delete" v-on:click="del()"></button>
  Staus of order nr {{nr}} has been changed 
</div>
</template>

<script>
export default {
  created() {
    this.$root.$on("eve", data => {
      this.nr = data;
    });
    Echo.private("order" + this.nr).listen("status_changed", e => {
      this.sn = true;
    });
  },
  props: [],

  data: function() {
    return {
      sn: false,
      nr: 0
    };
  },
  methods: {
    del: function() {
      this.sn = false;
    }
  }
};
</script>

Here is the problem. Variable nr is 0 all time. It'not changing dynamically. When nr is static or channel is public this code works fine. Please help.

1

There are 1 answers

1
Roy J On

Put the Echo inside the $on. Otherwise the asynchronous $on happens too late to change nr in the Echo.

  created() {
    this.$root.$on("eve", data => {
      this.nr = data;
      Echo.private("order" + this.nr).listen("status_changed", e => {
        this.sn = true;
      });
    });
  }