How to Build a Real-time Chat App with Laravel, Vue.js, and Pusher

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

Next, install Laravel Breeze using the command below.


composer require laravel/breeze 

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

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

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

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

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=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
BROADCAST_CONNECTION=pusher

Ensure you replace , , , and 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 

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.




namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;

use IlluminateDatabaseEloquentModel;

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');

    }

}

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.




use IlluminateDatabaseMigrationsMigration;

use IlluminateDatabaseSchemaBlueprint;

use IlluminateSupportFacadesSchema;

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');

    }

};

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

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.




use IlluminateSupportFacadesAuth;

use IlluminateSupportFacadesBroadcast;

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

    return Auth::check();

});

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

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.




namespace AppEvents;

use AppModelsChatMessages;

use IlluminateBroadcastingChannel;

use IlluminateBroadcastingInteractsWithSockets;

use IlluminateBroadcastingPresenceChannel;

use IlluminateBroadcastingPrivateChannel;

use IlluminateContractsBroadcastingShouldBroadcast;

use IlluminateContractsBroadcastingShouldBroadcastNow;

use IlluminateFoundationEventsDispatchable;

use IlluminateQueueSerializesModels;

use AppModelsUser;

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

     */

    public function broadcastOn(): array

    {

        return [

            new PrivateChannel("chat"),

        ];

    }

    public function broadcastWith()

    {

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

    }

}

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

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.




namespace AppHttpControllers;

use AppEventsMessageSent;
use AppHttpControllersController;
use AppModelsChatMessages;
use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;

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);
    }
}

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 AppHttpControllersChatController;
use AppModelsUser;
use IlluminateSupportFacadesAuth;

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']);

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

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

The code above is a Vue.js component responsible for the chat functionality. The