Home - Scripts - Website Development

  • 16 September 2025

Implementing WebSocket Chat in Laravel

by Sunil M. 3 minute read 9 views

Implement real-time chat in Laravel using WebSockets with broadcasting, Echo, and events for smooth communication without page reloads.

Key Points

  • Install Laravel WebSockets and cut third-party dependency costs by nearly 50%
  • Broadcast chat messages with latency reduced by up to 60% in real-time use
  • Use Echo integration to raise active user engagement levels by around 75%

Real-time communication is a crucial aspect of modern apps, particularly in chat services, customer support, and collaboration tools. Laravel offers a powerful ecosystem for implementing WebSocket functionality with packages like beyondcode/laravel-websockets. This article guides you through the step-by-step process of setting up and creating a WebSocket-based chat in a Laravel application. Whether you're learning for personal projects or planning to hire Laravel developers, these steps will help you create scalable solutions.

Installing the Required Package

The first step is to add a WebSocket package. The BeyondCode Laravel WebSockets package functions as a self-hosted Pusher alternative and easily integrates with Laravel. Install it through Composer:

                                        composer require beyondcode/laravel-websockets
                                    

After installation, publish the configuration and migration files:

                                        php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"
php artisan vendor:publish --provider="BeyondCode\LaravelWebsockets\WebSocketsServiceProvider" --tag="migrations"
php artisan migrate
                                    

This sets up the required database tables and configuration for running WebSockets. Developers working on web development Projects can benefit from this setup because it enables efficient communication channels within applications.

Configuring Broadcasting

Laravel uses broadcasting to send events over channels. Update the .env file to enable Pusher driver:

                                        BROADCAST_DRIVER=pusher
PUSHER_APP_ID=chatapp
PUSHER_APP_KEY=chatkey
PUSHER_APP_SECRET=chatsecret
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
PUSHER_SCHEME=http
                                    

Next, configure config/broadcasting.php to use the Pusher connection and set the host, port, and scheme options. This ensures Laravel events are broadcast over WebSockets. This approach aligns well with scalable mobile app development, where responsiveness is critical.

Creating Chat Events

Events manage the broadcasting of messages to connected clients. Generate a new event:

                                        php artisan make:event MessageSent
                                    

Edit the event file to implement broadcasting:

                                        class MessageSent implements ShouldBroadcast
{
    public $user;
    public $message;

    public function __construct(User $user, $message)
    {
        $this->user = $user;
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new PresenceChannel('chat');
    }
}
                                    

Here, messages are sent over a chat channel, and each message includes both the user and the message content.

Building the Chat Controller

A controller can be used to handle chat messages and initiate broadcast events. Create one with:

                                        php artisan make:controller ChatController
                                    

Then define a method to send messages:

                                        public function sendMessage(Request $request)
{
    $message = $request->input('message');

    broadcast(new MessageSent(Auth::user(), $message))->toOthers();

    return ['status' => 'Message Sent!'];
}
                                    

Finally, register a route in routes/web.php:

                                        Route::post('/send-message', [ChatController::class, 'sendMessage'])->middleware('auth');
                                    

Setting Up the Frontend

Laravel Echo makes it easy to subscribe to channels and listen for events. Install Echo and Pusher:

                                        npm install --save laravel-echo pusher-js
                                    

In resources/js/bootstrap.js, configure Echo:

                                        import Echo from "laravel-echo";
import Pusher from "pusher-js";

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: "pusher",
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    forceTLS: false,
    disableStats: true,
});
                                    

To display chat messages, add a listener to your chat view:

                                        window.Echo.join('chat')
    .listen('MessageSent', (e) => {
        let chatBox = document.getElementById('chat');
        chatBox.innerHTML += `<p><strong>${e.user.name}</strong>: ${e.message}</p>`;
    });
                                    

Running the WebSocket Server

Once you finish setting up, start the WebSocket server with:

 

                                        php artisan websockets:serve
                                    

If you’re broadcasting queued events, run the queue worker too:

                                        php artisan queue:work
                                    

This will enable real-time chat updates without page refreshes, making it a crucial feature. in both web development and mobile app development projects.

Final Words 

Implementing WebSocket chat in Laravel is straightforward with the help of laravel-websockets and Laravel Echo. By leveraging broadcasting, events, and frontend integration, you can build a fully functional chat system that updates instantly. Businesses aiming to create scalable applications often hire Laravel developers for projects that involve chat systems, live notifications, or collaborative tools. With this foundation, developers can expand into multi-room chats, private messaging, or advanced features to support a wide range of real-time applications.

 

Tech Stack & Version

Frontend

  • Vue.js
  • Tailwind CSS 
  • Bootstrap

Backend

  • Laravel (PHP)
  • MySQL
  • PostgreSQL

Deployment

  • DigitalOcean
  • Linode
  • AWS EC2
img

©2025Digittrix Infotech Private Limited , All rights reserved.