Docs.
Twelve sections. Read the first two for the idea, then sections 04 to 07 and you can send a message.
The problem.
Realtime in Laravel means running your own infrastructure and handling each direction separately.
| 1. A socket server | Laravel Echo Server, Soketi or similar. You install it, keep it running, and put it behind your proxy. |
| 2. Redis | The socket server and Laravel talk through Redis, so you run that too. |
| 3. A frontend setup | Echo and the client library, configured to match the server. |
| 4. Two channels for one conversation | Laravel can broadcast events from your server to browsers. The way back is plain AJAX calls to your own routes. |
| 5. A listener command | To catch what browsers send to each other, you write a command that subscribes to Redis and keep it alive with Supervisor. That is a second long-running process next to the first. |
Two processes to run, a Redis to secure, and a frontend that talks to your server in two different ways.
The idea.
RealtimeHub is a SignalR hub. Your frontend connects to it directly and messages travel both ways on that one connection. Your Laravel app never holds a socket open.
Your backend does one thing: it asks the hub for a token for the signed-in user. After that the browser talks to the hub.
| You need | What you set up | What runs on your server |
|---|---|---|
| Client to client | One route that returns a token (section 05). | Nothing extra. No Redis, no socket server, no command. |
| Your server to clients | One call with your app secret (section 07). | Nothing extra. No connection to hold open. |
| Client to your server | Turn on the webhook for the app and add one env value (section 10). | Nothing extra. The hub calls a route in your app for each message. |
The other direction works too. Your backend can send a message to any user with one call and your secret, with no connection to keep open (section 07).
Concepts.
| App | One product of yours. It has a key, a secret, allowed origins, schemas and settings. An account can have three. |
| App key | A public id that starts with rhk_. Your backend sends it when it asks for a token. |
| Secret | A private value that starts with rhs_. It is shown once when you create the app. It lives on your backend and nowhere else. |
| User id | The id of a signed-in user in your own system. 1 to 128 characters from A-Z a-z 0-9 _ - . : @. |
| Token | Proof that one user belongs to one app. Valid for one hour unless you ask for a different time. Your frontend gets it from your backend. |
| Channel | A room you name yourself, such as trips.21. Users join it when they connect, and a message sent to it reaches everyone in it. 1 to 64 characters from A-Z a-z 0-9 _ - .. |
| Event | The name of a kind of message, such as chat or typing. Up to 100 characters from A-Z a-z 0-9 _ - . :. |
Quick start.
- Sign in and create an app in the dashboard. Copy the key and the secret.
- Put both on your backend as configuration. The secret never goes to a browser.
- Add a route that asks the hub for a token for the signed-in user (section 05).
- Load the browser client and connect with that token (section 06).
- Call
sendand listen withonEvent(section 07).
The app page in the dashboard has a Quickstart tab with these steps filled in with your own key and app id.
Get a token.
Your backend calls the hub with the secret and names the user. The hub returns a token for that user.
curl -X POST https://realtime.easylift.pk/api/token \
-H "Authorization: Bearer YOUR_APP_SECRET" \
-H "Content-Type: application/json" \
-d '{"appKey":"YOUR_APP_KEY","userId":"42"}'
{"token":"eyJhbGciOi...","expiresAtUtc":"2026-11-21T10:00:00Z"}
ttlSecondsis optional. The default is 3600. The minimum is 60 and the maximum is 86400.- The token is checked when a connection opens. A connection that is already open keeps working after the token expires. A reconnect needs a fresh token, which the browser client fetches on its own.
- A wrong secret, an unknown app key and an inactive app all return
401. A bad user id returns400. More than 300 requests a minute from one address returns429.
// config/hub.php
return [
'url' => env('HUB_URL', 'https://realtime.easylift.pk'),
'key' => env('HUB_KEY'), // YOUR_APP_KEY
'secret' => env('HUB_SECRET'), // the secret shown once in the dashboard
];
// routes/web.php
use Illuminate\Support\Facades\Http;
Route::get('/hub-token', function () {
$hub = config('hub');
return Http::withToken($hub['secret'])
->post($hub['url'].'/api/token', [
'appKey' => $hub['key'],
'userId' => (string) auth()->id(),
])->throw()->json();
})->middleware('auth');
app.get('/hub-token', requireLogin, async (req, res) => {
const r = await fetch(`${process.env.HUB_URL}/api/token`, {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.HUB_SECRET}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
appKey: process.env.HUB_KEY,
userId: String(req.user.id),
}),
});
res.status(r.status).json(await r.json());
});
Take the user id from your own session, never from the request. Whoever controls the user id controls who they appear to be.
Browser client.
The hub serves a small wrapper around the SignalR browser library. It caches the token, reconnects with backoff, and retries a first connection that fails.
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@8.0.7/dist/browser/signalr.min.js"></script>
<script type="module">
import { createRealtimeClient } from 'https://realtime.easylift.pk/sdk/realtimehub-client.js';
const client = createRealtimeClient({
hubUrl: 'https://realtime.easylift.pk/hub/chat',
fetchToken: () => fetch('/hub-token').then((r) => r.json()),
onEvent: (m) => console.log(m.from, m.event, m.payload),
onStatus: (s) => console.log('status', s),
});
await client.start();
const sent = await client.send('bob', 'chat', { text: 'hello' });
console.log(sent.id, sent.persisted);
</script>
| Option or method | What it does |
|---|---|
hubUrl | The hub address followed by /hub/chat. |
fetchToken | Returns { token, expiresAtUtc }. Usually a call to your /hub-token route. |
channels | Optional list of channels to join when the connection opens. |
onEvent(message) | Called for every message addressed to this user or sent to a channel they are in. |
onStatus(status, error) | connecting, connected, reconnecting or disconnected. |
start() | Resolves when connected. |
send(userId, event, payload) | Resolves with { id, timestampUtc, persisted }. Rejects with the reason when the hub refuses the message. |
onPresence({ channel, userId, type }) | Someone joined or left a channel you are in. type is join or leave. |
joinChannel(name), leaveChannel(name) | Change channels after connecting. Joined channels are joined again after a reconnect. joinChannel resolves with who is in the channel. |
getPresence(name) | Resolves with { channel, count, users } for a channel you are in. |
sendToChannel(name, event, payload) | Sends to everyone in a channel you are in. Same result and errors as send. |
stop() | Closes the connection and stops reconnecting. |
React Native and other non-browser apps can use the official SignalR client for their platform with the same URL and token.
Send and receive.
A message goes from one user to one user in the same app. The hub sets from from the token, so a client cannot send as someone else.
{
"id": "9f2c6e1a4b7d4c0a8e3d5b6a7c8d9e0f",
"from": "alice",
"to": "bob",
"event": "chat",
"payload": { "text": "hello" },
"timestampUtc": "2026-11-21T09:00:32.296Z"
}
- Every open connection of the recipient receives it, so a user with two tabs sees it in both.
- A user who is offline does not receive it later. Send messages to your own server (section 10) if you need a record.
- A message to your own user id reaches your own connections, so you can test with one account.
- Users in other apps never receive it, even with the same user id.
Channels
A channel is a room you name yourself. There is nothing to create: it exists while someone is in it. One connection can be in up to 20 channels.
const client = createRealtimeClient({
hubUrl: 'https://realtime.easylift.pk/hub/chat',
fetchToken,
channels: ['trips.21'], // joined when the connection opens
onEvent: (m) => console.log(m.channel ?? 'direct', m.from, m.event, m.payload),
});
await client.start();
await client.joinChannel('alerts'); // join later
await client.sendToChannel('trips.21', 'trip.updated', { status: 'arrived' });
await client.leaveChannel('alerts');
- Without the browser client, add the channels to the connection address:
/hub/chat?channel=trips.21&channel=alerts. The hub methods areJoinChannel,LeaveChannelandSendToChannel. - A channel message has
channelset and noto. A user can only send to a channel they are in. The sender hears their own message. - By default any user can join any channel of your app. To decide who may join what, list the channels when you ask for the token. The user can then join those and nothing else. An empty list means no channels. A channel in the address that the token does not allow closes the connection.
curl -X POST https://realtime.easylift.pk/api/token \
-H "Authorization: Bearer YOUR_APP_SECRET" \
-H "Content-Type: application/json" \
-d '{"appKey":"YOUR_APP_KEY","userId":"42","channels":["trips.21"]}'
Your backend can send to a channel with channel in place of to, even when nobody is in it yet:
curl -X POST https://realtime.easylift.pk/api/send \
-H "Authorization: Bearer YOUR_APP_SECRET" \
-H "Content-Type: application/json" \
-d '{"appKey":"YOUR_APP_KEY","channel":"trips.21","event":"trip.updated","payload":{"status":"arrived"}}'
use Ohad\RealtimeHub\Facades\RealtimeHub;
RealtimeHub::broadcast('trips.21', 'trip.updated', ['status' => 'arrived']);
A channel message counts as one message however many people are in it. Channel messages are not saved and are not sent to your webhook.
Presence
The hub knows who is in each channel. It counts users, not connections, so a user with two tabs is one member. They join when their first tab joins and leave when their last tab closes.
const client = createRealtimeClient({
hubUrl: 'https://realtime.easylift.pk/hub/chat',
fetchToken,
channels: ['trips.21'],
onPresence: ({ channel, userId, type }) => console.log(userId, type, channel), // type: 'join' or 'leave'
});
await client.start();
const { count, users } = await client.getPresence('trips.21'); // who is here now
joinChannelalso returns who is in the channel, you included.getPresence(channel)asks again later. You can only ask about a channel you are in.- Joins and leaves arrive as messages from
$serverwith the event$presence.joinor$presence.leaveand the payload{ "userId": "..." }. With the browser client they go toonPresenceinstead ofonEvent. You are never told about yourself. A user who connects at the same moment you join can be announced even though they were already in the list you got, so apply each event as adding or removing that user from a set. No client can send an event name that starts with$, so these cannot be faked. countis exact.userslists up to 1,000, sorted.- Joining and leaving use your connection's message rate, so a client that joins and leaves in a loop is rate limited. Presence messages are not counted against the app's message rate.
- Your backend can ask too:
curl "https://realtime.easylift.pk/api/channels/trips.21/presence?appKey=YOUR_APP_KEY" \
-H "Authorization: Bearer YOUR_APP_SECRET"
{"channel":"trips.21","count":2,"users":["ann","bob"]}
use Ohad\RealtimeHub\Facades\RealtimeHub;
$here = RealtimeHub::presence('trips.21'); // ['channel' => 'trips.21', 'count' => 2, 'users' => ['ann', 'bob']]
Presence is kept in memory on the hub server. A restart empties it, and clients that reconnect join again. It is per server, which is how this hub runs today.
From your server
Your backend can send a message to users without a connection. It calls the hub with the same app secret it uses for tokens.
curl -X POST https://realtime.easylift.pk/api/send \
-H "Authorization: Bearer YOUR_APP_SECRET" \
-H "Content-Type: application/json" \
-d '{"appKey":"YOUR_APP_KEY","to":["42","57"],"event":"notification","payload":{"text":"Your order shipped"}}'
{"id":"9f2c6e1a4b7d4c0a8e3d5b6a7c8d9e0f","timestampUtc":"2026-11-21T09:00:32.296Z","recipients":2}
REALTIMEHUB_URL=https://realtime.easylift.pk
REALTIMEHUB_APP_KEY=YOUR_APP_KEY
REALTIMEHUB_APP_SECRET=<the secret shown once>
use Ohad\RealtimeHub\Facades\RealtimeHub;
// one user, or an array of up to 50
RealtimeHub::send($order->user_id, 'notification', ['text' => 'Your order shipped']);
RealtimeHub::send([$a->id, $b->id], 'notification', ['text' => 'New comment']);
tois one user id or an array of up to 50. The receiver gets the message inonEventwithfromset to$server. No client can use that id, so a message from$serveralways came from your backend.recipientsin the response is how many users the message was accepted for. The hub cannot tell whether a user is online, so it does not mean that many people received it. A user who is offline does not get it later.- The same rules apply as for a client message: event names, 32 KB payload, schemas and strict mode.
- Each recipient counts as one message against the app's rate (100 a second by default). A call that would pass the limit is refused whole, and nothing is sent.
- Messages you send are not saved to your database and are not sent to your webhook, so they never come back to your own server.
- A wrong key or secret, a paused app and a suspended account all return
401. A bad request returns400with the reason inerror, a payload over 32 KB returns413, and the rate limit returns429.
Allowed origins.
A browser can only connect from a website you list on the app: scheme, host and port, no path. For example https://app.example.com or http://localhost:3000. An app can list 20.
Mobile apps and servers send no Origin header and are accepted on the strength of the token alone.
Schemas.
Give an event a JSON Schema and every payload for that event is checked before delivery. A payload that does not match is rejected, and the sender gets the reason.
{
"type": "object",
"required": ["text"],
"properties": {
"text": { "type": "string", "minLength": 1, "maxLength": 500 },
"replyTo": { "type": "string" }
},
"additionalProperties": false
}
Payload does not match the schema for 'chat': /text: Value is "integer" but should be "string"
- Define schemas in the dashboard, under the app's Schemas tab. The tester there runs the same check the hub runs.
- An event with no schema accepts any payload. Turn on strict mode and an event with no schema is rejected.
- A schema can be up to 64 KB and an app can describe up to 50 events.
$refworks for references inside the same schema, such as#/$defs/name. References to other URLs are refused.- The regular expression keywords
patternandpatternPropertiesare not supported yet. Useenum,const,minLength,maxLength,minimum,maximumortype.
Get messages into Laravel.
Live delivery forgets a message once it is delivered. To act on a message in your own backend, or to keep it, use the webhook. It fires the RealtimeEventReceived event in Laravel and saves to the realtime_events table by default.
Webhook. Nothing to run.
The hub sends each message to a URL in your app. Your app needs one route, which the package adds for you.
- Open the app's Persistence tab, enter your URL, for example
https://yourapp.com/realtimehub/events, and turn the webhook on. The signing secret is shown once. - Install the Laravel package from GitHub.
- Put the signing secret in your
.env. The route exists as soon as the secret is set. - Press Send a test event on the Persistence tab. The result shows right there.
composer config repositories.realtimehub vcs https://github.com/raheelshan/realtimehub-laravel
composer require ohad/realtimehub-laravel:^2.0
php artisan vendor:publish --tag=realtimehub-config
php artisan vendor:publish --tag=realtimehub-migrations
php artisan migrate
REALTIMEHUB_WEBHOOK_SECRET=<the signing secret shown above>
// app/Providers/AppServiceProvider.php, in boot()
Event::listen(\Ohad\RealtimeHub\Events\RealtimeEventReceived::class, function ($e) {
match ($e->eventName) {
'chat' => \App\Models\Message::create(['from' => $e->from, 'to' => $e->to, 'text' => $e->payload['text']]),
default => null,
};
});
- The hub sends up to 50 messages in one request, in order, signed with your secret. The package checks the signature and the timestamp for you.
- Delivery is at least once. A message can arrive twice, so use the message id as a key. The saved row already does.
- If your server does not answer with a 2xx, the hub tries the same messages again after 30 seconds, 2 minutes, 10 minutes and 30 minutes. After the fifth failure it sets them aside, shows the count on the Persistence tab, and moves on.
- Messages set aside after the fifth failure are counted on the Persistence tab. They are not sent again, so fix the cause of the failures quickly.
- The test event is named
realtimehub.test, and the package saves it like any other message. - Your listener runs while the hub waits, up to 10 seconds. Keep it quick. Put heavy work on a Laravel queue, which needs a queue worker.
- Messages sent while no URL is saved are not delivered later. The hub starts from the moment you turn the webhook on.
- An app that sends very fast while its server stays down for hours can lose the oldest messages, because the hub keeps about 10,000 per app.
Errors and limits.
Message from send | Cause |
|---|---|
| Not connected to the hub. | Call start() first, or wait for connected. |
| Rate limit exceeded. | One connection sent more than 10 messages a second (burst 20). |
| App rate limit exceeded. | All connections of the app together passed the app limit (100 a second, burst 200, by default). |
| Invalid toUserId. / Invalid eventName. | The id or the name uses characters outside the allowed set. |
| Join the channel before asking who is in it. | Presence can only be asked for a channel you are in. |
| Join the channel before sending to it. | A client can only send to channels it is in. |
| This token does not allow that channel. | The token request listed channels and this one was not among them. |
| Payload exceeds 32768 bytes. | The payload JSON is larger than 32 KB. |
| Payload does not match the schema for '<event>': ... | The payload failed the schema. The text after the colon says where. |
| Event '<event>' has no schema and this app requires one. | Strict mode is on and the event is not described. |
| App is not active. | The app was paused or the account was suspended. |
Limits
| Open connections per app | 1,000 |
| Messages per second per app | 100, burst 200 |
| Messages per second per connection | 10, burst 20 |
| Channels per connection | 20 |
| Payload | 32 KB of JSON |
| Event schemas per app | 50, each up to 64 KB |
| Allowed origins per app | 20 |
| Token requests | 300 a minute per address |
Change the connection and message limits of an app on its page in the dashboard.
Security.
- The secret stays on your backend. If it leaks, rotate it in the dashboard. The old one stops working at once.
- Only the hash of the secret is stored. We cannot show it again, so keep a copy.
- Use HTTPS for the hub and for your own site.
- Take the user id for a token from your session. Never trust one sent by the browser.
- Anything a user's browser sends can be forged, so treat a message from a user as untrusted input. Only a message from
$serveris guaranteed to come from your backend. - List only the origins you use. Remove
http://localhostentries from a live app. - Webhook requests are signed with a secret only you and the hub know. Your app rejects any request with a wrong signature or a timestamp older than 5 minutes.
- The hub only calls public https addresses. A webhook URL that points at a private network or a cloud metadata address is refused, and redirects are not followed.