Building a Real-Time Chat Application with Livewire 3.0

Real-Time Chat in Livewire 3.0

Introduction

In last blog Adding Notifications and Toast Messages in Livewire 3.0, we explored how to add notifications and toast messages in Livewire 3.0. Today, we’ll dive into building a real-time chat application using Livewire 3.0. Real-time chat apps are integral to modern web applications, enabling seamless communication between users. With Livewire’s reactivity, creating such a feature becomes simple and efficient.

Step 1: Setting Up the Chat Environment

1. Create a Chat Component

Generate a new Livewire component for the chat feature:


php artisan make:livewire Chat

This creates:

  1. app/Livewire/Chat.php – The backend logic for the chat.

  2. resources/views/livewire/chat.blade.php – The frontend view for the chat interface.

Step 2: Defining Chat Logic

Open Chat.php and define properties and methods:


<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Message;
use Illuminate\Support\Facades\Auth;

class Chat extends Component
{
    public $messages;
    public $newMessage;

    protected $listeners = ['messageReceived' => 'fetchMessages'];

    public function mount()
    {
        $this->fetchMessages();
    }

    public function fetchMessages()
    {
        $this->messages = Message::latest()->take(20)->get()->reverse();
    }

    public function sendMessage()
    {
        $this->validate([
            'newMessage' => 'required|max:255',
        ]);

        Message::create([
            'user_id' => Auth::id(),
            'content' => $this->newMessage,
        ]);

        $this->newMessage = '';

        $this->emit('messageReceived');
    }

    public function render()
    {
        return view('livewire.chat');
    }
}

What’s Happening Here?

  1. fetchMessages: Fetches the latest 20 messages from the database.

  2. sendMessage: Validates and saves new messages to the database.

  3. $listeners: Listens for the messageReceived event to update messages in real time.

Step 3: Designing the Chat Interface

Open chat.blade.php and build the chat layout:



<div>
    <div class="chat-box">
        @foreach ($messages as $message)
            <div class="message {{ $message->user_id === auth()->id() ? 'self' : '' }}">
                <strong>{{ $message->user->name }}:</strong> {{ $message->content }}
            </div>
        @endforeach
    </div>

    <form wire:submit.prevent="sendMessage" class="chat-input">
        <input type="text" wire:model="newMessage" placeholder="Type your message...">
        <button type="submit">Send</button>
    </form>
</div>

<style>
    .chat-box {
        height: 300px;
        overflow-y: scroll;
        border: 1px solid #ddd;
        padding: 10px;
        margin-bottom: 10px;
    }
    .message {
        margin-bottom: 10px;
    }
    .message.self {
        text-align: right;
    }
    .chat-input {
        display: flex;
        gap: 10px;
    }
    .chat-input input {
        flex: 1;
        padding: 8px;
        border: 1px solid #ddd;
    }
    .chat-input button {
        padding: 8px 12px;
        background-color: blue;
        color: white;
        border: none;
        cursor: pointer;
    }
</style>

Step 4: Setting Up the Database

1. Create a Migration

Run the following command:


php artisan make:migration create_messages_table

In the migration file, define the schema:


Schema::create('messages', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->text('content');
    $table->timestamps();
});

Run the migration:


php artisan migrate

2. Create the Message Model


php artisan make:model Message

Update Message.php:


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'content'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Step 5: Broadcasting Messages (Optional)

For real-time broadcasting, you can use Laravel Echo and Pusher:

  1. Install Laravel Echo and Pusher:


npm install --save laravel-echo pusher-js

Configure broadcasting in .env:


BROADCAST_DRIVER=pusher
PUSHER_APP_ID=your-app-id
PUSHER_APP_KEY=your-app-key
PUSHER_APP_SECRET=your-app-secret
PUSHER_APP_CLUSTER=your-cluster

Update the sendMessage method to broadcast events:


event(new MessageSent($message));

Listen for the broadcast event in your JavaScript:


Echo.channel('chat')
    .listen('MessageSent', (e) => {
        Livewire.emit('messageReceived');
    });

Final Output

By following these steps, your chat application will:

  1. Allow users to send and receive messages in real time.

  2. Dynamically update the message list without refreshing the page.

  3. Provide an interactive and user-friendly experience.

Key Features Covered Today

  1. Creating a real-time chat application with Livewire 3.0.

  2. Managing messages dynamically with Livewire properties.

  3. Setting up the database for chat functionality.

  4. (Optional) Integrating real-time broadcasting with Laravel Echo.


© Copyright 2025 Wontonee. All Right Reserved.

×How can I help you?