Build a Real-Time Chat App with Laravel and Reverb

Build a Real-Time Chat App with Laravel and Reverb

Build a Real-Time Chat App with Laravel and Reverb

Build a fully functional real-time chat app where messages appear instantly for all participants — no page refresh needed.

Features

  • Real-time messaging with Laravel Reverb (WebSockets)
  • Private and group chat rooms
  • Online presence indicators
  • Message read receipts
  • Livewire components for reactive UI

Step 1 — Install Reverb

php artisan install:broadcasting
# Choose Reverb when prompted
php artisan reverb:start

Step 2 — Message Event

// app/Events/MessageSent.php
class MessageSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(public Message $message) {}

    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('chat.' . $this->message->room_id),
        ];
    }

    public function broadcastWith(): array
    {
        return [
            'id'        => $this->message->id,
            'body'      => $this->message->body,
            'user'      => $this->message->user->name,
            'avatar'    => $this->message->user->avatar_url,
            'timestamp' => $this->message->created_at->diffForHumans(),
        ];
    }
}

Step 3 — Livewire Chat Component

class ChatRoom extends Component
{
    public Room $room;
    public string $body = '';
    public Collection $messages;

    public function mount(): void
    {
        $this->messages = $this->room->messages()
            ->with('user')
            ->latest()
            ->take(50)
            ->get()
            ->reverse();
    }

    #[On('echo-private:chat.{room.id},MessageSent')]
    public function onMessageReceived(array $event): void
    {
        $this->messages->push((object) $event);
    }

    public function send(): void
    {
        $message = $this->room->messages()->create([
            'user_id' => auth()->id(),
            'body'    => $this->body,
        ]);

        broadcast(new MessageSent($message))->toOthers();
        $this->body = '';
    }
}
All Comments