Building a Real-Time Chat Application with Laravel WebSocket

A real-time chat application is an excellent example of how WebSocket can revolutionize real-time interactive communication on the web. In this article, we'll walk through building a simple chat application using Laravel and integrating WebSocket using the laravel-websockets package to deliver responsive and interactive communication experiences to users.

Objectives of the Application

We will build a real-time chat application with the following features:

Send and Receive Messages Instantly: Users can send and receive messages instantly without needing to refresh the page.

Online User List: The application will display a list of online users and their chat status.

Send Images and Files: Users can share images and files within the chat.

Getting Started with Installation and Configuration

To get started, we need to install the laravel-websockets package and configure it to integrate WebSocket with Laravel. Follow these steps:

Install the laravel-websockets package: Begin by installing the package using Composer.

composer require pusher/pusher-php-server

Publish the configuration file: After installation, publish the configuration file to customize the settings.

 

php artisan vendor:publish --tag=websockets-config

Run migration: Create the necessary database tables for WebSocket.

php artisan migrate

Start WebSocket server: Launch the WebSocket server to handle real-time connections

php artisan websockets:serve

Building the User Interface

We'll create a simple user interface using HTML, CSS, and JavaScript to display the message list, input box, and the list of online users.

<!-- resources/views/chat.blade.php -->

<div id="app">
    <div class="chat-container">
        <div class="chat-box">
            <div class="chat-messages">
                <div class="message" v-for="message in messages" :key="message.id">
                    {{ message.user }}: {{ message.content }}
                </div>
            </div>
            <div class="input-box">
                <input v-model="newMessage" @keydown.enter="sendMessage" placeholder="Enter your message...">
            </div>
        </div>
    </div>
</div>

Integrating WebSocket and Broadcasting

We'll use Laravel Broadcasting to integrate WebSocket with the application.

Install Pusher: Install the pusher/pusher-php-server package to use Pusher as the Broadcasting driver.

composer require pusher/pusher-php-server

Configure Broadcasting: In the config/broadcasting.php file, configure the driver and provide your Pusher credentials.

'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'),
        'encrypted' => true,
    ],
],

Create an event and broadcast: Create a ChatMessageSent event and broadcast it when a user sends a message.

// app/Events/ChatMessageSent.php

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

JavaScript Script: Use JavaScript to listen for events from the server and update the user interface.

// resources/js/app.js

require('./bootstrap');

import Vue from 'vue';
import Chat from './components/Chat.vue';

const app = new Vue({
    el: '#app',
    components: {
        Chat
    }
});

Conclusion

By completing this tutorial, you've successfully built a real-time chat application using WebSocket in Laravel. Users can send and receive messages instantly, and you've witnessed how WebSocket provides a responsive and interactive communication experience.