In our previous Laravel tutorial, we have explained how to develop To-do list app with Vue.js and Laravel. In this tutorial, we will explain to develop RealTime Chat Application with Laravel and WebSockets.
RealTime Chat app is an app in which real-time communication is made between multiple users. Here in this tutorial, we will use WebSocket that lets you establish a two-way communication system in real-time between a user device and your server.
So lets proceed with implementation,
1. Prerequisites
- PHP (>= 7.3)
- Composer installed
- Node.js and npm for front-end dependencies
2. Create Laravel App
After above installation, we will create our Laravel application.
composer create-project laravel/laravel realtime-chat-app
we will move to the project directory.
cd realtime-chat-app
3. Install Laravel WebSockets
We will install the Laravel WebSockets package. The package allows to use WebSockets without needing a third-party service like Pusher.
composer require beyondcode/laravel-websockets
After installing, we will publish the WebSockets configuration file using below command:
php artisan vendor:publish --tag=websockets-config
The above will create the websockets.php file in config folder. Now we can configure our WebSocket server in this file.
We will also update the config/broadcasting.php file with below code to set up Pusher as broadcast driver, but make sure to use WebSockets internally instead of an external service.
'connections' => [ 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'useTLS' => true, 'encrypted' => true, 'host' => '127.0.0.1', 'port' => 6001, 'scheme' => 'http', ], ], ],
We will also update the .env file with Pusher credentials:
PUSHER_APP_ID=your-app-id PUSHER_APP_KEY=your-key PUSHER_APP_SECRET=your-secret PUSHER_APP_CLUSTER=mt1
4. Set Up WebSocket Server
Now, we will update websockets.php configuration file to as per our needs. As the default settings are often sufficient for development, but still ensure that the dashboard and apps section is properly set up.
'apps' => [ [ 'id' => env('PUSHER_APP_ID'), 'name' => env('APP_NAME'), 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'path' => '', 'capacity' => null, 'enable_client_messages' => true, 'enable_statistics' => true, ], ],
5. Create Chat Events
Now, we will create a new Event that will handle broadcasting messages to the WebSocket server.
We will use below command for this:
php artisan make:event MessageSent
After executing above command, we will update the MessageSent.php event class to implement the ShouldBroadcast interface. This interface will broadcast the event over WebSockets.
namespace App\Events; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Queue\SerializesModels; class MessageSent implements ShouldBroadcast { use InteractsWithSockets, SerializesModels; public $message; public function __construct($message) { $this->message = $message; } public function broadcastOn() { return ['chat-channel']; } public function broadcastAs() { return 'message.sent'; } }
6. Setup Chatroom Frontend
Now, we will install Pusher JS and Laravel Echo for frontend WebSocket handling.
npm install --save pusher-js laravel-echo
After installing above, we will create a resources/js/bootstrap.js file and add the following configuration.
import Echo from 'laravel-echo'; window.Pusher = require('pusher-js'); window.Echo = new Echo({ broadcaster: 'pusher', key: process.env.MIX_PUSHER_APP_KEY, wsHost: window.location.hostname, wsPort: 6001, forceTLS: false, disableStats: true, }); window.Echo.channel('chat-channel') .listen('.message.sent', (e) => { console.log(e.message); // Append the new message to the chat window });
7. Create a Chat View
Now, we will create a our chat view interface where users can send and receive messages. We will add below code to routes/web.php file.
Route::get('/chat', function () { return view('chat'); });
Then we will create the resources/views/chat.blade.php view.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chat App</title> </head> <body> <div id="chat"> <ul id="messages"></ul> <input id="message-input" type="text" placeholder="Type a message"> <button onclick="sendMessage()">Send</button> </div> <script src="{{ mix('js/app.js') }}"></script> <script> function sendMessage() { const message = document.getElementById('message-input').value; // Send the message to the server axios.post('/send-message', { message: message }); } window.Echo.channel('chat-channel') .listen('.message.sent', (e) => { const messages = document.getElementById('messages'); const newMessage = document.createElement('li'); newMessage.textContent = e.message; messages.appendChild(newMessage); }); </script> </body> </html>
8. Handle Sending Messages
Now, we will handle the actual sending of the messages. we will add below code to the routes/web.php this to create route.
Route::post('/send-message', function (Request $request) { event(new \App\Events\MessageSent($request->message)); return response()->json(['status' => 'Message Sent!']); });
9. Running the WebSocket Server
We will compile the frontend asset before running our application.
npm run dev
Then we will run the WebSocket server.
php artisan websockets:serve
Then we will run the Laravel’s development server.
php artisan serve
Now finally, our chat application will be available on http://localhost:8000/chat in web browser.