How to Build a Real-Time Chat Application with Laravel and React
Introduction
Real-time messaging has become an essential feature of modern web applications. From customer support platforms and collaboration tools to social networking applications, users expect messages to appear instantly without refreshing the page.
In this tutorial, we will learn how to build a real-time chat application using Laravel and React. We will create a backend API, store chat messages in a MySQL database, broadcast messages using WebSockets, and display new messages instantly in a React frontend.
Instead of repeatedly sending requests to check for new messages, our application will use WebSocket connections to receive updates automatically.
By the end of this tutorial, you will understand how to:
- Create a Laravel backend for a chat application.
- Store chat rooms and messages in MySQL.
- Configure Laravel Reverb for real-time communication.
- Broadcast chat messages using Laravel events.
- Connect React to Laravel using Laravel Echo.
- Send and receive messages instantly.
- Understand how to extend the application with authentication, typing indicators, and online status.
1. Technologies Required
We will use the following technologies to build our chat application.
Technology | Purpose |
|---|---|
Laravel | Backend API and business logic |
PHP | Server-side programming |
MySQL | Store users, chat rooms, and messages |
React | Build the chat user interface |
Laravel Reverb | WebSocket server |
Laravel Echo | Listen for real-time events |
Vite | Frontend development and build tool |
How the architecture works
When a user sends a message, React sends it to the Laravel API. Laravel validates the request and saves the message in the database. After saving, Laravel broadcasts an event through Reverb.
Other connected users subscribed to the same chat room receive the event through Laravel Echo, and React updates the chat interface immediately.
User A (React)
|
| HTTP POST message
v
Laravel API
|
| Save message
v
MySQL Database
|
| Broadcast event
v
Laravel Reverb (WebSocket)
|
| Real-time event
v
User B (React + Laravel Echo)
This architecture allows users to communicate without constantly refreshing the page.
2. Create the Laravel Backend
First, make sure you have PHP, Composer, Node.js, and MySQL installed on your development machine.
Create a new Laravel project:
composer create-project laravel/laravel chat-backend cd chat-backend
Configure your database in the .env file:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=chat_app DB_USERNAME=root DB_PASSWORD=
Create a MySQL database named chat_app and run the migrations:
php artisan migrate
Laravel will create the default database tables required for the application.
3. Configure Real-Time Broadcasting with Laravel Reverb
Laravel Reverb is Laravel's first-party WebSocket server that allows applications to communicate in real time.
Install the broadcasting configuration and Reverb:
php artisan install:broadcasting
Follow the installer prompts to configure Reverb.
The installation will configure the broadcasting system and install the required packages. Review your .env file to make sure broadcasting is configured correctly.
Example configuration:
BROADCAST_CONNECTION=reverb REVERB_APP_ID=chat-app REVERB_APP_KEY=chat-app-key REVERB_APP_SECRET=chat-app-secret REVERB_HOST=127.0.0.1 REVERB_PORT=8080 REVERB_SCHEME=http
The values shown above are examples. Use the actual credentials generated by your installation.
Start the Reverb server:
php artisan reverb:start
For development, Reverb can run in a terminal while you work on your Laravel application.
4. Create the Chat Room and Message Tables
We need two database tables:
chat_rooms— stores chat room information.chat_messages— stores messages sent inside chat rooms.
Create the models and migrations:
php artisan make:model ChatRoom -m php artisan make:model ChatMessage -m
Chat room migration
Open the migration file for chat_rooms and add:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('chat_rooms', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('chat_rooms');
}
};
Chat message migration
Open the chat_messages migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('chat_messages', function (Blueprint $table) {
$table->id();
$table->foreignId('chat_room_id')
->constrained('chat_rooms')
->cascadeOnDelete();
$table->foreignId('user_id')
->nullable()
->constrained()
->nullOnDelete();
$table->string('sender_name');
$table->text('message');
$table->timestamps();
$table->index(['chat_room_id', 'created_at']);
});
}
public function down(): void
{
Schema::dropIfExists('chat_messages');
}
};
We are using user_id as a nullable foreign key so this tutorial can demonstrate messages without requiring a complete authentication system.
For production applications, messages should be connected to authenticated users and the sender name should come from the authenticated account rather than the request.
Run the migrations:
php artisan migrate
5. Configure the Laravel Models
Open app/Models/ChatRoom.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ChatRoom extends Model
{
protected $fillable = [
'name',
];
public function messages(): HasMany
{
return $this->hasMany(ChatMessage::class);
}
}
Open app/Models/ChatMessage.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ChatMessage extends Model
{
protected $fillable = [
'chat_room_id',
'user_id',
'sender_name',
'message',
];
public function room(): BelongsTo
{
return $this->belongsTo(ChatRoom::class, 'chat_room_id');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
These relationships allow us to retrieve chat messages associated with a room and users associated with messages.
6. Create a Real-Time Message Event
Laravel events allow us to broadcast information when something happens in our application.
Create a message event:
php artisan make:event MessageSent
Open app/Events/MessageSent.php and replace its contents:
<?php
namespace App\Events;
use App\Models\ChatMessage;
use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, SerializesModels;
public function __construct(
public ChatMessage $message
) {}
public function broadcastOn(): array
{
return [
new Channel('chat.' . $this->message->chat_room_id),
];
}
public function broadcastAs(): string
{
return 'message.sent';
}
public function broadcastWith(): array
{
return [
'id' => $this->message->id,
'chat_room_id' => $this->message->chat_room_id,
'user_id' => $this->message->user_id,
'sender_name' => $this->message->sender_name,
'message' => $this->message->message,
'created_at' => $this->message->created_at,
];
}
}
Understanding the event
ShouldBroadcasttells Laravel that this event should be broadcast.broadcastOn()defines the channel where the event is sent.broadcastAs()defines the custom event name.broadcastWith()defines the data sent to connected clients.
We are using a public channel for this basic example. A production chat application should use private channels and authorization to ensure that only members of a chat room can read its messages.
7. Create the Chat API Controller
Create a controller:
php artisan make:controller ChatController
Open app/Http/Controllers/ChatController.php:
<?php
namespace App\Http\Controllers;
use App\Events\MessageSent;
use App\Models\ChatMessage;
use App\Models\ChatRoom;
use Illuminate\Http\Request;
class ChatController extends Controller
{
public function rooms()
{
return ChatRoom::query()
->select('id', 'name')
->orderBy('id')
->get();
}
public function messages(ChatRoom $room)
{
return $room->messages()
->orderBy('id')
->limit(100)
->get();
}
public function sendMessage(Request $request, ChatRoom $room)
{
$validated = $request->validate([
'sender_name' => ['required', 'string', 'max:100'],
'message' => ['required', 'string', 'max:5000'],
]);
$message = $room->messages()->create([
'sender_name' => $validated['sender_name'],
'message' => $validated['message'],
]);
broadcast(new MessageSent($message))->toOthers();
return response()->json($message, 201);
}
}
What happens when a message is sent?
- Laravel receives the request.
- The request is validated.
- The message is stored in MySQL.
- Laravel broadcasts the
MessageSentevent. - Other users in the chat room receive the event.
- Laravel returns the saved message to the sender.
The toOthers() method prevents broadcasting the same message back to the sender, who already receives the saved message in the API response.
8. Configure the API Routes
Open routes/api.php and add:
<?php
use App\Http\Controllers\ChatController;
use Illuminate\Support\Facades\Route;
Route::get('/chat/rooms', [ChatController::class, 'rooms']);
Route::get('/chat/rooms/{room}/messages', [
ChatController::class,
'messages',
]);
Route::post('/chat/rooms/{room}/messages', [
ChatController::class,
'sendMessage',
]);
The API endpoints are now:
Method | Endpoint | Purpose |
|---|---|---|
GET |
| Get chat rooms |
GET |
| Get room messages |
POST |
| Send a message |
Create a test chat room
You can create a chat room using Laravel Tinker:
php artisan tinker
Then execute:
\App\Models\ChatRoom::create([
'name' => 'General Chat'
]);
Exit Tinker:
exit
Your first chat room is ready.
9. Create the React Frontend
Now we will create the frontend application.
npm create vite@latest chat-frontend -- --template react cd chat-frontend npm install
Install Laravel Echo and the Pusher-compatible client used by Reverb:
npm install laravel-echo pusher-js
Laravel Reverb uses the Pusher protocol, which allows Laravel Echo to connect to the WebSocket server.
10. Configure Laravel Echo
Create a file:
src/echo.js
import Echo from "laravel-echo";
import Pusher from "pusher-js";
window.Pusher = Pusher;
const echo = new Echo({
broadcaster: "reverb",
key: import.meta.env.VITE_REVERB_APP_KEY,
wsHost: import.meta.env.VITE_REVERB_HOST,
wsPort: Number(import.meta.env.VITE_REVERB_PORT || 8080),
wssPort: Number(import.meta.env.VITE_REVERB_PORT || 8080),
forceTLS: import.meta.env.VITE_REVERB_SCHEME === "https",
enabledTransports: ["ws", "wss"],
});
export default echo;
Configure the frontend environment file .env:
VITE_API_URL=http://127.0.0.1:8000/api VITE_REVERB_APP_KEY=chat-app-key VITE_REVERB_HOST=127.0.0.1 VITE_REVERB_PORT=8080 VITE_REVERB_SCHEME=http
Use the actual Reverb application key and host from your Laravel configuration.
11. Build the React Chat Interface
Open src/App.jsx and replace the default Vite application:
import { useEffect, useState } from "react";
import echo from "./echo";
import "./App.css";
const API_URL = import.meta.env.VITE_API_URL;
export default function App() {
const [rooms, setRooms] = useState([]);
const [roomId, setRoomId] = useState(null);
const [messages, setMessages] = useState([]);
const [senderName, setSenderName] = useState("");
const [message, setMessage] = useState("");
useEffect(() => {
fetch(`${API_URL}/chat/rooms`)
.then((response) => response.json())
.then((data) => {
setRooms(data);
if (data.length > 0) {
setRoomId(data[0].id);
}
})
.catch(console.error);
}, []);
useEffect(() => {
if (!roomId) return;
fetch(`${API_URL}/chat/rooms/${roomId}/messages`)
.then((response) => response.json())
.then(setMessages)
.catch(console.error);
const channel = echo.channel(`chat.${roomId}`);
channel.listen(".message.sent", (newMessage) => {
setMessages((previous) => {
if (previous.some((item) => item.id === newMessage.id)) {
return previous;
}
return [...previous, newMessage];
});
});
return () => {
echo.leave(`chat.${roomId}`);
};
}, [roomId]);
async function sendMessage(event) {
event.preventDefault();
if (!message.trim() || !senderName.trim() || !roomId) {
return;
}
try {
const response = await fetch(
`${API_URL}/chat/rooms/${roomId}/messages`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
sender_name: senderName,
message: message.trim(),
}),
}
);
if (!response.ok) {
throw new Error("Unable to send message");
}
const savedMessage = await response.json();
setMessages((previous) => {
if (previous.some((item) => item.id === savedMessage.id)) {
return previous;
}
return [...previous, savedMessage];
});
setMessage("");
} catch (error) {
console.error(error);
alert("Message could not be sent.");
}
}
return (
<div className="chat-app">
<aside className="sidebar">
<h2>Chat Rooms</h2>
{rooms.map((room) => (
<button
key={room.id}
className={roomId === room.id ? "active" : ""}
onClick={() => setRoomId(room.id)}
>
{room.name}
</button>
))}
</aside>
<main className="chat-main">
<header className="chat-header">
<h2>Real-Time Chat</h2>
<p>Messages appear instantly.</p>
</header>
<div className="messages">
{messages.map((item) => (
<div className="message" key={item.id}>
<strong>{item.sender_name}</strong>
<p>{item.message}</p>
<small>
{new Date(item.created_at).toLocaleTimeString()}
</small>
</div>
))}
</div>
<form className="chat-form" onSubmit={sendMessage}>
<input
type="text"
placeholder="Your name"
value={senderName}
onChange={(event) => setSenderName(event.target.value)}
/>
<input
type="text"
placeholder="Write a message..."
value={message}
onChange={(event) => setMessage(event.target.value)}
/>
<button type="submit">Send</button>
</form>
</main>
</div>
);
}
12. Add CSS Styling
Open src/App.css:
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: Arial, sans-serif;
background: #f3f4f6;
}
.chat-app {
display: flex;
height: 100vh;
background: #ffffff;
}
.sidebar {
width: 260px;
padding: 20px;
border-right: 1px solid #e5e7eb;
background: #111827;
color: white;
}
.sidebar h2 {
margin-top: 0;
}
.sidebar button {
display: block;
width: 100%;
margin: 8px 0;
padding: 12px;
border: 0;
border-radius: 6px;
color: white;
text-align: left;
background: #374151;
cursor: pointer;
}
.sidebar button.active {
background: #2563eb;
}
.chat-main {
display: flex;
flex: 1;
flex-direction: column;
min-width: 0;
}
.chat-header {
padding: 20px;
border-bottom: 1px solid #e5e7eb;
}
.chat-header h2 {
margin: 0 0 5px;
}
.chat-header p {
margin: 0;
color: #6b7280;
}
.messages {
flex: 1;
padding: 20px;
overflow-y: auto;
}
.message {
width: fit-content;
max-width: 80%;
margin-bottom: 15px;
padding: 12px 16px;
border-radius: 10px;
background: #e5efff;
}
.message p {
margin: 8px 0;
overflow-wrap: anywhere;
}
.message small {
color: #6b7280;
}
.chat-form {
display: flex;
gap: 10px;
padding: 15px;
border-top: 1px solid #e5e7eb;
}
.chat-form input {
min-width: 0;
padding: 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
}
.chat-form input:nth-child(1) {
width: 150px;
}
.chat-form input:nth-child(2) {
flex: 1;
}
.chat-form button {
padding: 12px 20px;
border: 0;
border-radius: 6px;
background: #2563eb;
color: white;
cursor: pointer;
}
@media (max-width: 700px) {
.sidebar {
width: 120px;
padding: 10px;
}
.chat-form {
flex-wrap: wrap;
}
.chat-form input {
width: 100% !important;
}
}
13. Run the Application
Start the Laravel API:
php artisan serve
Start the Reverb WebSocket server in another terminal:
php artisan reverb:start
Start the React frontend:
npm run dev
Open the React application in your browser.
To test real-time messaging:
- Open the application in one browser window.
- Open the same application in another browser or incognito window.
- Enter different sender names.
- Select the same chat room.
- Send a message from the first browser.
- Observe the message appear instantly in the second browser without refreshing.
If the message is saved in MySQL but not appearing in the other browser, check the Reverb server, frontend WebSocket configuration, broadcast connection, and browser console.
14. Add Authentication and Private Chat Rooms
The example above demonstrates the basic real-time messaging functionality. A production application should include authentication and room authorization.
You can use Laravel Sanctum to authenticate users and protect the API endpoints.
Additional features to implement include:
- User registration and login.
- Private chat rooms.
- Group conversations.
- Private WebSocket channels.
- Message read receipts.
- Typing indicators.
- Online and offline status.
- User profile images.
- Message search.
- File and image sharing.
- Push notifications.
- Rate limiting and abuse protection.
For private chat rooms, use Laravel's private broadcasting channels and authorize each user to join only the rooms where they are a member.
15. Deploy Your Real-Time Chat Application
When deploying to a production server, the Laravel application, database, React frontend, and WebSocket server must be configured correctly.
Important deployment requirements include:
- Configure your production MySQL database.
- Build the React frontend using
npm run build. - Configure Laravel environment variables.
- Use HTTPS for the website and secure WebSockets (
wss://). - Configure Reverb behind a reverse proxy such as Nginx.
- Keep Reverb running using a process manager such as Supervisor.
- Configure CORS correctly for the frontend domain.
- Protect API endpoints with authentication and rate limits.
- Configure queue workers if you use queued broadcasting.
- Monitor logs and WebSocket connection errors.
A WebSocket server should not be treated like a normal one-time PHP request. It needs to stay running so clients can maintain active connections.
16. Common Problems and Solutions
Messages are saved but other users cannot receive them
Check that the broadcasting connection is set to Reverb, that the WebSocket server is running, and that your React Echo configuration uses the correct hostname, port, and application key.
WebSocket connection fails
Verify the Reverb host, port, scheme, and firewall settings. For production, ensure your reverse proxy supports WebSocket connections.
React receives duplicate messages
The sender receives the saved message from the HTTP response, while other users receive the broadcast. Use message IDs to prevent duplicate entries.
API request fails because of CORS
Configure the Laravel CORS settings to allow requests from the frontend domain. Do not allow every origin in a production application that uses credentials.
Messages do not appear after changing rooms
Make sure the frontend leaves the previous channel and subscribes to the new room channel. Also reload the messages for the selected room.
17. Conclusion
Building a real-time chat application with Laravel and React is a practical way to understand modern web application architecture.
Laravel provides the API, validation, database operations, and event broadcasting. React creates the interactive frontend, while Laravel Reverb and Laravel Echo allow users to receive messages instantly through WebSockets.
The basic application can be extended into a customer support chat system, team messaging application, social chat platform, or real-time collaboration tool.
If you are developing a web application, ERP, CRM, or custom business software and need real-time communication features, understanding this architecture can help you build scalable and responsive applications.
GSS Technology develops web applications, ERP systems, business software, and custom digital solutions for businesses.
Explore our software development services to learn more about our development solutions.
Frequently Asked Questions
1. Can I build a real-time chat application with Laravel and React?
Yes. Laravel can manage users, messages, database operations, and broadcasting, while React provides the interactive chat interface. Laravel Reverb and Laravel Echo can deliver messages in real time.
2. What is Laravel Reverb?
Laravel Reverb is Laravel's first-party WebSocket server that enables real-time communication between a Laravel application and connected clients.
3. Do I need WebSockets for a chat application?
WebSockets are recommended for real-time chat because they allow the server to send new messages to connected clients without requiring repeated polling requests.
4. Is Laravel suitable for chat applications?
Yes. Laravel offers database management, authentication, events, broadcasting, queues, and WebSocket integration, making it a suitable framework for building chat applications.
5. Can I use React with Laravel for real-time messaging?
Yes. React can communicate with Laravel through APIs and listen for real-time broadcast events using Laravel Echo.
6. How can I make a Laravel chat application secure?
Use authentication, private channels, authorization policies, validation, rate limiting, secure WebSocket connections, and appropriate access control to protect chat messages and user data.




