Create dynamic channels using Laravel echo and broadcasting

2.1k views Asked by At

I'm trying to create a chat in which users can create 1 to 1 conversations or even group conversations. I'm using Laravel 5.5 and Vue.js.

From what I read from the documentation to join a chat with a wild card is possible:

Echo.join('chat.'{roomId})
        //.here()
        //.joining()
        //.leaving()
        .listen('MessagePosted', (e) => {
            //Some action
        });
});

and in routes/channels.php I should use

Broadcast::channel('chat.{roomId}', function ($user, $roomId) {
    //some form of authentication
});

But where should I place the Echo function?

I'm creating the Vue app with

const app = new Vue({
el: '#app',
data: {
    //Some arrays
},
methods: {
    //some methods
},
created() {
    //some axios functions to happen when it is created

    Echo.join('chatroom')
        //.here()
        //.joining()
        //.leaving()
        .listen('MessagePosted', (e) => {
            console.log(e);
            this.messages.push({
                message: e.message.message,
                user: e.user
            });
        });

}

});

As you can see I used to create a general channel in which every instance created with #app would join. But I want to change that to join just a certain channel.

1

There are 1 answers

0
Carlos F On BEST ANSWER

Easier than I thought.

Just created method that will be called whenever I wish to change the channel, for example, a different window chat. Place the function inside the methods

showThread(thread) {
    Echo.leave(/*The last channel*/);
    Echo.join(/*New room*/)
        .listen('MessagePosted', (e) =>{/*actions*/}

Not sure if it the best practice to call it constantly but it works. If anyone finds this and has a question or suggestion I would gladly hear it.