Laravel Echo is great artisan make: event ChatMessageWasReceived

Applications or Websockets cannot be missing. You can make Tool chat online, Notification, … and many other real time applications. With Laravel Echo everything becomes simpler.

Idea

Build online chat function with multiple rooms.

Visualize before doing

Online Chat application will definitely need a WebSocket to listen to the data sent. Ok use laravel-echo-server for it blood. The client when receiving data from Broadcasting will display data directly to the user, playing Vuejs.

Let's start

First create an event in Laravel

Check if there are any new files app / Events / ChatMessageWasReceived.php done!

In the file there is an important method

For simplicity I will not use Private channel anymore but use Public channel in this article to change it again as follows

Next, the chat application must have a place to store data.

The content is quite simple

Go back to the class app / Events / ChatMessageWasReceived.php passing some parameters as follows

Remember that Implements ShouldBroadcast interface.

Ok then I will now use Command to send a message to the client. Create 1 command

A newly created file app / Console / Commands / SendChatMessage.php has the following content

Open app / Console / Kernel.php and add params as follows

Ok so that's done Now every time we send a message we will use the following command

Ok where will this message be sent, I will send it to a websocket to receive data like above I said will use laravel-echo-server

When we have completed the laravel-echo-server package

Initialize for the project

It will generate a laravel-echo-server.json file. You configure that file according to your environment. Here I will use redis as db and the broadcast open port 6001 default.

Open .env file and configure broadcast as follows

Launch WebSocket

You can check the port 6001 has worked offline with linux

If you see port 6001 is listening, it is already successful. * _ ^

Next config continues for the client to receive the information. Open resouces / assets / js / app.js and add the following content

It's okay now, let's run gulp or gulp watch .

Insert the following HTML 2 javascript file

So done. You can test it

The above message will be stored in the database and transmitted to WebSocket via port 6001 using TCP protocol and then sent back to the client so Laravel Echo receives the message and displays it to you through consolog . Every time a message is sent, consolog displays the data immediately. The article is quite long then I will not give specific instructions to complete a chat application using vuejs. I will save it for later. Thank you for reading. Wish you success!

Reference

The article has references through documents

https://mattstauffer.co/blog/introducing-laravel-echo https://laravel.com/docs/5.3/broadcasting#defining-broadcast-events https://laracasts.com/lessons/introducing-laravel-echo

ITZone via Viblo

Share the news now