
Fermin Perdomo
Full Stack Developer

How to Build a Real-time SMS Chat App with Laravel, Inertiajs, React, and Pusher
PHP 8.3 (or higher) installed
Node and NPM installed
Composer installed globally
A Pusher account. Click here to create an account if you don't have one
Basic knowledge of WebSockets
Basic knowledge of the Inertiajs framework would be nice, but is not essential
Next, install Laravel Breeze using the command below.Once the Laravel Breeze installation is complete, scaffold the authentication for the application. Do that by running the following commands one after the other.When prompted, select the options below.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.When prompted, select these options: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 and the application running my application with Laravel Herk.Once the application server is up, open http://sms-chat-app.test/ 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.The next step is to open the project in your preferred IDE or text editor.Configure PusherPusher 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 react inertiajs client.Install the Pusher helper library by running the command below in a new terminal instance or tab.
Then, in your Pusher dashboard, create a new app by clicking Create App under Channels.Next, fill out the form, as in the screenshot below, and click Create app.
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: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 TwilioTwilio is a cloud communications platform that enables developers to integrate messaging, voice, video, and other communication capabilities into their applications using APIs. It allows businesses to send SMS, make phone calls, handle VoIP, implement two-factor authentication, and more without needing to build their own telecom infrastructure.Install the Twilio helper library by running the command below in a new terminal instance or tab.Then, in your Twilio console, to get the account information Acount SID, Auth Token, My Twilio phone number. Now, locate the .env file in the root directory of your project. Add the following lines to the bottom of the file:
TWILIO_CONNECTION
- The name of the default Twilio API connection for your application; if using a single connection this does not need to be changed
TWILIO_NOTIFICATION_CHANNEL_CONNECTION
- If using Laravel's notifications system, the name of a Twilio API connection to use in the notification channel (defaulting to your default connection); if using a single connection this does not need to be changed
TWILIO_API_SID
- The Twilio API SID to use for the default Twilio API connection
TWILIO_API_AUTH_TOKEN
- The Twilio API authentication token to use for the default Twilio API connection
TWILIO_API_FROM_NUMBER
- The default sending phone number to use for the default Twilio API connection, note the sending phone number can be changed on a per-message basis
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.Open app/Models and update the content of ChatMessages.php with this.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.Update the file that ends with create_users_table.php with the following code.In this migration we add a new field to allow add phone_number in the user table.After updating the models and migration,s the next step is to run the migration. Do that by running the command below in your terminal.Setup the event broadcastNext, set up the event broadcast by navigating to channels.php file in the routes folder and update it with the following.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.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.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 controllerThe 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.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.In the code above, the necessary imports required for the chat application are added. 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.Open the TwilioController.php file and replace the content with the following.In the code above, we are storing the message in the database and sending the notification to update the chat in real time.Twilio reply setupExpose your local server to allow recieve incoming messages.setup the url on the twilio webhook web store incoming message:Update the routesNow, 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.Next, replace the dashboard route with the following .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 setupNow that the backend part of the chat application is fully set up, it’s time to build the user interface of the chat application.Create a new React componentNext, 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.import InputError from '@/Components/InputError';
import { Transition } from '@headlessui/react';
import { useForm } from '@inertiajs/react';
import { FormEventHandler, useEffect, useRef, useState } from 'react';
interface Message {
id: number;
sender_id: number;
receiver_id: number;
text: string;
created_at: string;
}
interface ChatBoxProps {
sender: { id: number };
receiver: { id: number };
initialMessages: Message[];
}
const ChatBox: React.FC<ChatBoxProps> = ({
sender,
receiver,
initialMessages,
}) => {
const [messages, setMessages] = useState<Message[]>(initialMessages);
const messagesBox = useRef<HTMLDivElement>(null);
const { data, setData, post, errors, processing, recentlySuccessful } =
useForm({
message: '',
});
const submit: FormEventHandler = (e) => {
e.preventDefault();
post(route('messages.store', receiver.id));
setData('message', '');
setMessages((prevMessages) => [
...prevMessages,
{
id: 0,
sender_id: sender.id,
receiver_id: receiver.id,
text: data.message,
created_at: new Date().toISOString(),
},
]);
};
useEffect(() => {
if (window.Echo) {
console.log('echo set');
window.Echo.private('chat').listen(
'MessageSent',
(response: { message: Message }) => {
console.log('sent', response);
if (response.message) {
setMessages((prevMessages) => [
...prevMessages,
response.message,
]);
}
},
);
}
}, [receiver.id, sender.id]);
useEffect(() => {
if (messagesBox.current) {
messagesBox.current.scrollTop = messagesBox.current.scrollHeight;
}
}, [messages]);
const formatTimestamp = (timestamp: string) => {
const date = new Date(timestamp);
return `${date.getHours()}:${date.getMinutes()}`;
};
return (
<div className="mx-auto flex h-[500px] w-full max-w-md flex-col border p-4">
<div
ref={messagesBox}
className="flex flex-1 flex-col overflow-y-auto p-3"
>
{messages.map((message, index) => (
<div
key={index}
className={`my-1 max-w-xs rounded-lg p-2 ${
message.sender_id === sender.id
? 'self-end bg-blue-100 text-blue-800'
: 'self-start bg-gray-200 text-gray-800'
}`}
>
{message.text}
<span className="ml-2 text-xs text-gray-500">
{formatTimestamp(message.created_at)}
</span>
</div>
))}
</div>
<form onSubmit={submit}>
<div className="flex border-t p-2">
<input
type="text"
value={data.message}
onChange={(e) => setData('message', e.target.value)}
placeholder="Type a message..."
className="flex-1 rounded-lg border p-2"
/>
<InputError className="mt-2" message={errors.message} />
<button
disabled={processing}
className="ml-2 rounded-lg bg-blue-500 px-4 py-2 text-white"
>
Send
</button>
<Transition
show={recentlySuccessful}
enter="transition ease-in-out"
enterFrom="opacity-0"
leave="transition ease-in-out"
leaveTo="opacity-0"
>
<p className="text-sm text-gray-600 dark:text-gray-400">
Saved.
</p>
</Transition>
</div>
</form>
</div>
);
};
export default ChatBox;Update the Echo.js fileAfter 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
});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.Update the Blade templatesThe final step in the frontend setup is updating the dashboard page. Navigate to resources/js/Pages and update dashboard.tsx with the below content.import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head } from '@inertiajs/react';
interface User {
id: number;
name: string;
email: string;
}
interface DashboardProps {
auth: {
user: User;
};
users: User[];
}
export default function Dashboard({ auth, users }: DashboardProps) {
return (
<AuthenticatedLayout
header={
<h2 className="text-xl font-semibold leading-tight text-gray-800 dark:text-gray-200">
Dashboard
</h2>
}
>
<Head title={auth.user.name} />
<div className="py-12">
<div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
<div className="overflow-hidden bg-white shadow-sm sm:rounded-lg dark:bg-gray-800">
<div className="p-6 text-gray-900 dark:text-gray-100">
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
{users.map((user) => (
<div
key={user.id}
className="overflow-hidden bg-white shadow-sm sm:rounded-lg"
>
<div className="p-6">
<div className="flex items-center">
<a href={`/chat/${user.id}`}>
<div className="ml-4">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
{user.name}
</div>
<div className="text-sm text-gray-500 dark:text-gray-400">
{user.email}
</div>
</div>
</a>
</div>
</div>
</div>
))}
</div>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);In the updated Dashboard.tsx, 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/js/Pages, create a new file Chat.tsx and update it with the following content.import ChatBox from '@/Components/ChatBox';
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head } from '@inertiajs/react';
interface User {
id: number;
name: string;
email: string;
}
interface Message {
id: number;
sender_id: number;
receiver_id: number;
text: string;
created_at: string;
}
interface ChatProps {
receiver: User;
sender: User;
messages: Message[];
}
export default function Chat({ receiver, sender, messages }: ChatProps) {
return (
<AuthenticatedLayout
header={
<h2 className="text-xl font-semibold leading-tight text-gray-800 dark:text-gray-200">
Chat
</h2>
}
>
<Head title={sender.name} />
<div className="py-12">
<div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
<div className="overflow-hidden bg-white shadow-sm sm:rounded-lg dark:bg-gray-800">
<div
className="p-6 text-gray-900 dark:text-gray-100"
id="app"
>
<ChatBox
receiver={receiver}
sender={sender}
initialMessages={messages}
/>
</div>
</div>
</div>
</div>
</AuthenticatedLayout>
);
}This file holds the inertia component responsible for the chat functionality. It sets up the layout and includes the Chatbox
component, passing the authenticated user as the sender and the selected user as the receiver as props to it.Test the chat applicationIt’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:listenNext, 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. You can also use the SMS of you phone and will received or send the chat sms.That’s how to build a real-time SMS chat application using Laravel, Pusher, Twilio and, React inertiaThis tutorial has equipped you with the knowledge to effectively build a real-time SMS 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 React inertia 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!