DEV Community

Cover image for How to Build a Real-Time Chat App With Laravel, Vue.js, and Pusher
dami
dami

Posted on • Originally published at twilio.com

How to Build a Real-Time Chat App With Laravel, Vue.js, and Pusher

Real-time chat applications like WhatsApp and Discord have witnessed a remarkable surge in popularity in recent years, revolutionising communication with instantaneous messaging. However, while building your own chat app with this functionality might seem daunting, it’s entirely achievable.

In this tutorial, you will learn how to build a real-time chat application using Laravel, Vue.js, and Pusher. You'll use the Laravel framework to build the back end of the chat application, a combination of Blade templates and Vue.js to develop the user interface and layout of the application, and the Pusher platform for the real-time chat functionality.

Prerequisites

To complete this tutorial, you will need the following:

  • PHP 8.3 (or higher) installed

  • Node and NPM installed

  • Composer installed globally

  • A Pusher account. Create a new account here

  • Basic knowledge of WebSockets

  • Basic knowledge of the Vue.js framework would be nice, but is not essential

Backend setup

Begin by setting up all the necessary backend configurations required for the chat application.

Scaffold a new Laravel project

To get started with building your chat application, you need to create a new Laravel project using Composer and change into the project directory by running the below commands in your terminal.


composer create-project laravel/laravel chat-app

cd chat-app

Enter fullscreen mode Exit fullscreen mode

Next, install Laravel Breeze using the command below.


composer require laravel/breeze 

Enter fullscreen mode Exit fullscreen mode

Once the Laravel Breeze installation is complete, scaffold the authentication for the application. Do that by running the following commands one after the other.


php artisan breeze:install

npm install

npm run dev

Enter fullscreen mode Exit fullscreen mode

When prompted, select the options below.

Image description

The final step in the scaffolding process is to add the necessary packages and config files for WebSocket and event broadcast. Run the command below in a new terminal instance or tab.


php artisan install:broadcasting

Enter fullscreen mode Exit fullscreen mode

When prompted, select these options:

Image description

This command creates channels.php in the routes folder and broadcasting.php in the config folder. These files will hold the WebSocket configurations and install the necessary client libraries (Laravel Echo and pusher-js) needed to work with WebSockets.

With all of the scaffolding completed, start the application development server by running the commands below.


php artisan serve

Enter fullscreen mode Exit fullscreen mode

Once the application server is up, open http://localhost:8000/ in your browser. You should see the default Laravel welcome page with options to log in or register for your chat app, as shown in the image below.

Image description

The next step is to open the project in your preferred IDE or text editor.

Configure Pusher

Pusher is a cloud-hosted service that makes adding real-time functionality to applications easy. It acts as a real-time communication layer between servers and clients. This allows your backend server to instantly broadcast new data via Pusher to your Vue.js client.

Install the Pusher helper library by running the command below in a new terminal instance or tab.


composer require pusher/pusher-php-server

Enter fullscreen mode Exit fullscreen mode

Then, in your Pusher dashboard, create a new app by clicking Create App under Channels.

Image description

Next, fill out the form, as in the screenshot below, and click Create app.

Image description

After creating a new channels app, navigate to the App Keys section in the Pusher dashboard where you will find your Pusher credentials: App ID, Key, Secret, and Cluster. Note these values as you will need them shortly.

Now, locate the .env file in the root directory of your project. This file is used to keep sensitive data and other configuration settings out of your code. Add the following lines to the bottom of the file:


PUSHER_APP_ID=<your_pusher_app_id>
PUSHER_APP_KEY=<your_pusher_app_key>
PUSHER_APP_SECRET=<your_pusher_app_secret>
PUSHER_APP_CLUSTER=<your_pusher_app_cluster>
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
BROADCAST_CONNECTION=pusher
Enter fullscreen mode Exit fullscreen mode

Ensure you replace <your_pusher_app_id>, <your_pusher_app_key>, <your_pusher_app_secret>, and <your_pusher_app_cluster> with the actual values from your Pusher dashboard. Be careful to only replace the placeholder values with your actual credentials and do not alter the keys. This setup will enable your application to connect to Pusher's cloud servers and set Pusher as your broadcast driver.

Setup model and migration

After scaffolding the application, the next step is to create a model and a corresponding database migration. This will allow us to store chat messages and user information in the database. Run the following command in your terminal to create a model with a corresponding migration file.


php artisan make:model -m ChatMessages 

Enter fullscreen mode Exit fullscreen mode

This command will generate ChatMessages.php in the app/Models directory and a migration file in the database/Migrations directory.

Open app/Models and update the content of ChatMessages.php with this.


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class ChatMessages extends Model

{

    use HasFactory;

    protected $fillable = ['sender_id', 'receiver_id', 'text'];



    public function sender()

    {

        return $this->belongsTo(User::class, 'sender_id');  

    }

    public function receiver()

    {

        return $this->belongsTo(User::class, 'receiver_id');

    }

}

Enter fullscreen mode Exit fullscreen mode

In the code above, the $fillable property allows sender_id, receiver_id, and text to be mass-assigned. Additionally, the model defines two many-to-one relationships: the sender relationship links to the user model via the sender_id, and the receiver relationship links to the user model via receiver_id, representing the sender and receiver of the message, respectively.

Next, navigate to database/Migrations and update the file that ends with create_chat_messages_table.php with the following code.


<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

    /**

     \* Run the migrations.

     \*

    public function up(): void

    {

        Schema::create('chat_messages', function (Blueprint $table) {

            $table->id();

            $table->foreignId('sender_id')->constrained('users');

            $table->foreignId('receiver_id')->constrained('users');

            $table->string('text');

            $table->timestamps();

        });

    }

    /**

     \* Reverse the migrations.

     \*

    public function down(): void

    {

        Schema::dropIfExists('chat\_messages');

    }

};

Enter fullscreen mode Exit fullscreen mode

In the migration above, the database schema of the chat application is defined. This schema includes an id for each message, foreign keys sender_id and receiver_id that reference the users table, a text column to store the content of the message, and timestamp columns to record when each message is created and updated.

After updating the model and migration, the next step is to run the migration. Do that by running the command below in your terminal.


php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Setup the event broadcast

Next, set up the event broadcast by navigating to channels.php file in the routes folder and update it with the following.


<?php

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Broadcast;

Broadcast::channel('chat', function ($user) {

    return Auth::check();

});

Enter fullscreen mode Exit fullscreen mode

In the code above, a new broadcast channel named "chat" is defined, and a closure is passed to ensure that only authenticated users can subscribe to the channel.

After defining the channel, create a new event which will be broadcast to the client on the "chat" channel. Run the command below in your terminal to generate the event class.


php artisan make:event MessageSent

Enter fullscreen mode Exit fullscreen mode

The command will create a new file called MessageSent.php in the app/Events directory. Open the MessageSent.php file and update it with the below content.


<?php

namespace App\Events;

use App\Models\ChatMessages;

use Illuminate\Broadcasting\Channel;

use Illuminate\Broadcasting\InteractsWithSockets;

use Illuminate\Broadcasting\PresenceChannel;

use Illuminate\Broadcasting\PrivateChannel;

use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

use Illuminate\Foundation\Events\Dispatchable;

use Illuminate\Queue\SerializesModels;

use App\Models\User;

class MessageSent implements ShouldBroadcast

{

    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user, $chatMessage;

    /**

     \* Create a new event instance.

     \*

    public function __construct(User $user, ChatMessages $chatMessage)

    {

        $this->user = $user;

        $this->chatMessage = $chatMessage;

    }

    /**

     \* Get the channels the event should broadcast on.

     \*

     \* @return array\<int, \\Illuminate\\Broadcasting\\Channel\>

     \*/

    public function broadcastOn(): array

    {

        return [

            new PrivateChannel("chat"),

        ];

    }

    public function broadcastWith()

    {

        return ['message' => $this->chatMessage];

    }

}

Enter fullscreen mode Exit fullscreen mode

In the code above, the user and the message are passed into the constructor. The broadcastOn() method specifies that the event will be broadcast on a private channel named "chat", while the broadcastWith() method adds the chat message to the broadcast payload.

Create the controller

The next step is to create a controller class that will contain all the application logic. To create the controller, run the command below in your terminal.


php artisan make:controller ChatController

Enter fullscreen mode Exit fullscreen mode

This command will create a new file called ChatController.php in the app/Http/Controllers folder.

Open the ChatController.php file and replace the content with the following.


<?php

namespace App\Http\Controllers;

use App\Events\MessageSent;
use App\Http\Controllers\Controller;
use App\Models\ChatMessages;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ChatController extends Controller
{
    public function index(User $user)
    {
        $messages = ChatMessages::with(['sender', 'receiver'])
            ->whereIn('sender_id', [Auth::id(), $user->id])
            ->whereIn('receiver_id', [Auth::id(), $user->id])
            ->get();
        return response()->json($messages);
    }

    public function store(User $user, Request $request)
    {
        $message = ChatMessages::create([
            'sender_id' => Auth::id(),
            'receiver_id' => $user->id,
            'text' => $request->message,
        ]);
        broadcast(new MessageSent($user, $message))->toOthers();
        return response()->json($message);
    }
}

Enter fullscreen mode Exit fullscreen mode

In the code above, the necessary imports required for the chat application are added. In the index() function, messages exchanged between the currently authenticated user and the specified user are retrieved while eager-loading the sender and receiver information using the relationships. In the store() function, a new message from the currently authenticated user to the specified user is saved to the database, and the MessageSent event is broadcasted on the chat channel.

Update the routes

Now, it's time to update the routing table. So, in the web.php file located in the routes folder, add the following imports at the beginning of the file.


use App\Http\Controllers\ChatController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

Enter fullscreen mode Exit fullscreen mode

Next, replace the dashboard route with the following*.*


Route::get('/dashboard', function () {
    return view('dashboard', [
      'users' => User::where('id', '!=', Auth::id())->get()
    ]);
})->middleware(['auth', 'verified'])->name('dashboard');

Route::get('/chat/{user}', function (User $user){
    return view('chat', [
        'user' => $user
    ]);
})->middleware(['auth', 'verified'])->name('chat');

Route::resource(
    'messages/{user}', 
    ChatController::class, ['only' => ['index', 'store']]
)->middleware(['auth']);

Enter fullscreen mode Exit fullscreen mode

These routes set up the necessary endpoints for the chat application. The /dashboard route displays a list of users, excluding the current user. The /chat/{user} route loads the chat interface for a selected user. The Route::resource line sets up routes for retrieving and sending messages using the ChatController.

Frontend setup

Now that the backend part of the chat application is fully set up, it’s time to build the user interface of the chat application.

Install Vue.js

First, install Vue.js and the necessary plugin to detect .vue files by running the following commands:


npm install vue vue-loader  

npm install --save-dev @vitejs/plugin-vue

Enter fullscreen mode Exit fullscreen mode

Create a new Vue.js component

Next, navigate to resources/js and create a new folder called components. In the newly created components folder, create a new file called ChatBox.vue. Update its content with the following.


<template>
    <div class="chat-box">
        <div ref="messagesBox" class="chat-messages">
            <div v-for="(message, index) in messages" :key="index" :class="['chat-message', { 'own-message': message.sender_id === sender.id }]">
                {{ message.text }}
                <span class="timestamp">{{ formatTimestamp(message.created_at) }}</span>
              </div>
            </div>
            <div class="chat-input">
              <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="Type a message..." />
              <button @click="sendMessage">Send</button>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import { nextTick, onMounted, ref, watch } from 'vue';
export default {
    props: {
        receiver: {
            type: Object,
            required: true,
        },
        sender: {
            type: Object,
            required: true,
        },
    },
    setup(props) {
        const messages = ref([]);
        const newMessage = ref("");
        const messagesBox = ref(null);
        const scrollToBottom = () => {
            messagesBox.value.scrollTop = messagesBox.value.scrollHeight;
        };
        watch(
            messages,
            () => {
                nextTick(() => {
                    scrollToBottom();
                });
            },
            { deep: true }
        );
        const sendMessage = () => {
            if (newMessage.value.trim() !== "") {
                axios
                    .post(`/messages/${props.receiver.id}`, {
                        message: newMessage.value,
                    })
                    .then((response) => {
                        messages.value.push(response.data);
                        newMessage.value = ""; 
                    });
            }
        };
        const formatTimestamp = (timestamp) => {
            const date = new Date(timestamp);
            return `${date.getHours()}:${date.getMinutes()}`;
        };
        onMounted(() => {
            axios.get(`/messages/${props.receiver.id}`).then((response) => {
                messages.value = response.data;
            });
            Echo.private('chat')
                .listen("MessageSent", (response) => {
                    if (response.message) {
                        const messageExists = messages.value.some(msg => msg.id === response.message.id);
                        if (!messageExists) {
                            if ((response.message.sender_id === props.sender.id && response.message.receiver_id === props.receiver.id) || 
                                (response.message.sender_id === props.receiver.id && response.message.receiver_id === props.sender.id)) {
                                messages.value.push(response.message);
                            }
                        }
                    }
            });
        });
        return {
            messages,
            newMessage,
            messagesBox,
            sendMessage,
            formatTimestamp,
        };
    },
};
</script>

<style scoped>
.chat-box {
    display: flex;
    flex-direction: column;
    border: 1px solid #ccc;
    padding: 10px;
    margin: 0 auto;
    height: 500px;
}
.chat-messages {
    display: flex;
    flex: 1;
    flex-direction: column; 
    align-items: flex-start; 
    overflow-y: auto;
    padding: 15px;
}
.chat-input {
    display: flex;
    align-items: center;
    border-top: 10px;
}
.chat-input input {
    flex: 1;
    padding: 10px;
    margin-right: 5px;
}
.chat-input button {
    padding: 10px;
    border: 1px solid #0a0a0a;
}
.chat-message {
    display: inline-block;
    padding: 10px;
    margin: 5px 0;
    border-radius: 15px;
    word-wrap: break-word; 
}
.chat-message.own-message {
    align-self: flex-end;
    background-color: #d1e7ff;
    color: #0056b3;
    text-align: right;
}
.chat-message:not(.own-message) {
    align-self: flex-start;
    background-color: #e1e1e1;
    color: #333;
}
.timestamp {
    font-size: 0.8rem;
    color: #aaa;
    margin-left: 10px;
  }
</style>
Enter fullscreen mode Exit fullscreen mode

The code above is a Vue.js component responsible for the chat functionality. The <template> section defines the HTML structure, including a div for displaying messages and an input area for sending new messages, with each message conditionally styled to distinguish between messages sent by the current user and others.

In the <script> section, the receiver and sender are passed as [props](https://v2.vuejs.org/v2/guide/components-props) to identify the two users currently chatting. Within the setup function, reactive references messages, newMessage, and messagesBox are defined. The scrollToBottom() function ensures that the chat view always scrolls to display the latest message, while the sendMessage() function handles sending new messages to the server and updating the chat view accordingly.

The formatTimestamp() function formats the message timestamps for display. The onMounted lifecycle hook fetches existing messages and listens for the MessageSent event on the “chat” channel using Laravel Echo. Finally, the <style> section adds CSS styles to define the layout, the appearance of the messages, and the input area.

Update the Echo.js and App.js file

After creating the chat components, the next step is to update the JavaScript files. In the resources/js directory, locate the echo.js file and replace the content of the file with the following.


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,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
    forceTLS: true
});

Enter fullscreen mode Exit fullscreen mode

In the updated echo.js file, Echo is configured to use Pusher as the broadcaster for real-time events. It uses the key and cluster information specified earlier in our .env file to connect the application to the Pusher service.

Then, replace the content of the resources/js/app.js file with the content below


import './bootstrap';
import { createApp } from 'vue' 
import ChatBox from './components/ChatBox.vue' 

createApp({}) 
    .component('chat-box', ChatBox)
    .mount('#app')

Enter fullscreen mode Exit fullscreen mode

In the updated app.js file, the Vue.js application is set up by importing the necessary dependencies and creating a new instance. The ChatBox component is registered to the alias chat-box, and mounted to the HTML element with the id app, enabling the chat functionality in your application.

Update the vite.config.js file

Vite is a build tool that is responsible for building and bundling your frontend assets. You’ll need to update its config file so it can detect and build Vue.js components.

To do that, in the root directory, open the vite.config.js and update it with the following content:


import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue'; 

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
            ],
            refresh: true,
        }),
        vue({ 
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
    resolve: {
        alias: {
            vue: 'vue/dist/vue.esm-bundler.js',
        },
    }, 
});

Enter fullscreen mode Exit fullscreen mode

In the updated vite.config.js, the laravel-vite-plugin\ is configured to handle the CSS and JS files for your Laravel application. The @vitejs/plugin-vue\ plugin is also included to enable support for Vue.js single-file components. Additionally, the resolve\ section sets up an alias to use the Vue ES module build, which is necessary for single-file component support. This configuration ensures that Vite can properly process and serve your application during the development and build stages.

Update the Blade templates

The final step in the frontend setup is updating the Blade templates. Navigate to resources/views and update dashboard.blade.php with the below content.


<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{Auth::user()->name}} 
        </h2>
    </x-slot>
    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    <div class="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
                        @foreach ($users as $user)
                            <div class="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                                <div class="p-6">
                                    <div class="flex items-center">
                                        <a href="{{ route('chat', $user) }}">
                                            <div class="ml-4">
                                                <div class="text-sm font-medium text-gray-900 dark:text-gray-100">
                                                    {{ $user->name }}
                                                </div>
                                                <div class="text-sm text-gray-500 dark:text-gray-400">
                                                    {{ $user->email }}
                                                </div>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

Enter fullscreen mode Exit fullscreen mode

In the updated dashboard.blade.php, the list of users profiled on the system is returned, such that a logged-in user can chat with any of them.

Also in resources/views, create a new file chat.blade.php and update it with the following content.


<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{$user->name}}
        </h2>
    </x-slot>
    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100" id='app'>                       
                    <chat-box
                        :receiver = "{{ $user }}"
                        :sender = "{{ Auth::user() }}"
                    />
                </div>
            </div>
        </div>
    </div>
</x-app-layout>
Enter fullscreen mode Exit fullscreen mode

This file holds the Vue.js component responsible for the chat functionality. It sets up the layout and includes the chat-box\ component, passing the authenticated user as the sender and the selected user as the receiver as props to it.

Test the chat application

It’s finally time to see your chat app in action. By default Laravel events are dispatched on queues, therefore you’ll need to start up a queue worker instance so your event can be processed. Run the command below in your terminal to start your queue.


php artisan queue:listen

Enter fullscreen mode Exit fullscreen mode

Next, register two new users. Log in with one user in a regular browser tab, and log in with the other user in an incognito tab. Then, select each other on both tabs to start chatting.

Below is a video demonstration of the chat application.

Image description

That’s how to build a real-time chat application using Laravel, Pusher and, Vue.js

This tutorial has equipped you with the knowledge to effectively build a real-time chat application. You learned how to set up the backend logic and event broadcast using WebSockets with Laravel, handle real-time communication with Pusher, and build a dynamic frontend using Vue.js to listen for and display events.

With these skills, you can now create more complex real-time applications, or add additional features to your chat app. The possibilities are endless!

Keep building!

Top comments (0)