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
1 | php artisan make: event ChatMessageWasReceived |
Check if there are any new files app / Events / ChatMessageWasReceived.php done!
In the file there is an important method
1 2 3 4 | public function broadcastOn () { return new PrivateChannel ('channel-name'); } |
For simplicity I will not use Private channel anymore but use Public channel in this article to change it again as follows
1 2 3 4 5 6 | public function broadcastOn () { return [ "chat-room.1" ]; } |
Next, the chat application must have a place to store data.
1 | php artisan make: model ChatMessage --migration |
The content is quite simple
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | ... class CreateChatMessagesTable extends Migration { public function up () { Schema :: create ('chat_messages', function (Blueprint $ table) { $ table-> increments ('id'); $ table-> string ('message'); $ table-> integer ('user_id') -> unsigned (); $ table-> timestamps (); }); } public function down () { Schema :: drop ('chat_messages'); } } |
Go back to the class app / Events / ChatMessageWasReceived.php passing some parameters as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | ... ChatMessageWasReceived extends Event implements class ShouldBroadcast { use InteractsWithSockets, SerializesModels; public $ chatMessage; public $ user; public function __construct ($ chatMessage, $ user) { $ this-> chatMessage = $ chatMessage; $ this-> user = $ user; } public function broadcastOn () { return [ "chat-room.1" ]; } } |
Remember that Implements ShouldBroadcast interface.
Ok then I will now use Command to send a message to the client. Create 1 command
1 | php artisan make: command SendChatMessage |
A newly created file app / Console / Commands / SendChatMessage.php has the following content
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | ... class SendChatMessage extends Command { protected $ signature = 'chat: message {message}'; protected $ description = 'Send chat message.'; public function handle () { // Fire off an event, quá thường, lấy lại người dùng đầu để hiện thời $ user = App User :: first (); $ message = App ChatMessage :: create ([ 'user_id' => $ user-> id, 'message' => $ this-> argument ('message') ]); event (new Chat ChatMessageWasReceived ($ message, $ user)); } } |
Open app / Console / Kernel.php and add params as follows
1 2 3 4 5 6 7 | ... The Kernel class extends ConsoleKernel { protected $ commands = [ SendChatMessage :: class, ]; ... |
Ok so that's done Now every time we send a message we will use the following command
1 | php artisan chat: message "Howdy everyone" |
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
1 | npm install -g laravel-echo-server |
When we have completed the laravel-echo-server package
Initialize for the project
1 | laravel-echo-server init |
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
1 2 3 4 | BROADCAST_DRIVER = redis CACHE_DRIVER = file SESSION_DRIVER = file QUEUE_DRIVER = sync |
Launch WebSocket
1 | laravel-echo-server start |
You can check the port 6001 has worked offline with linux
1 | netstat -antp | grep LISTEN |
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
1 2 3 4 5 6 7 8 9 10 11 | import Echo from "laravel-echo" window.Echo = new Echo ({ broadcaster: 'socket.io', host: 'http://yourdomain.dev:6001' }); Echo.channel ('chat-room.1') .listen ('ChatMessageWasReceived', (e) => { console.log (e.user, e.chatMessage); }); |
It's okay now, let's run gulp or gulp watch .
Insert the following HTML 2 javascript file
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <head> ... <meta name = "csrf-token" content = "{{csrf_token ()}}"> ... </head> <body> ... <script src = "js / app.js"> </script> <script src = "https://cdn.socket.io/socket.io-1.4.5.js"> </script> </body> </html> |
So done. You can test it
1 | php artisan chat: message "Howdy everyone" |
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