Skip to content
Laravel Backend Software Architecture

SignalR for Laravel: Let the Browser Message Your PHP Directly

Raheel Shan

Raheel Shan

November 24th, 2026 · 18 min read

SignalR for Laravel: Let the Browser Message Your PHP Directly

My Laravel application no longer keeps a WebSocket connection open. It generates a token, and the browser connects directly to a hosted SignalR hub.

I built this because, after exploring several Laravel real-time setups, I still had one problem to solve: the browser sends a message through the connection, and my PHP application needs to process it.

That is the part I wanted to get working without adding another HTTP request from the browser or maintaining a separate Redis subscriber process, like the one in the previous article.

The gap, in one table

  • Pusher, laravel-websockets, echo-server: server to client yes. Client to server is a whisper (which does not reach PHP, see Why Laravel Echo Whispers Never Reach Your Server) or a separate HTTP request.
  • Reverb: server to client yes. Same client to server limitation.
  • Reverb + Redis: server to client yes. Client to server needs a separate subscriber process.
  • SignalR: server to client yes. Client to server through invoke(), which executes server-side code.

In the Laravel setups I covered in the previous articles, I needed two separate paths for communication: one for receiving messages and another for sending messages to the server. With SignalR, both directions can use the same connection.

The idea

RealtimeHub is a hosted SignalR hub. Each part has a specific responsibility:

  • The browser connects to the hub and sends and receives messages through one connection.
  • The hub delivers messages to users and channels. It can also forward one-to-one messages to your Laravel application.
  • Your Laravel application generates connection tokens, sends messages from the server, and processes messages received through the webhook.

Laravel does not maintain the WebSocket connection.

There is no Reverb process, no Redis server, no Supervisor configuration for a socket server, and no Laravel Echo. Article 1 started with seven moving parts. This is the opposite end of that.

Setup: the token route

The hub needs to know which user is connecting. Your backend provides that identity by generating a token.

First, create an application in the RealtimeHub dashboard. You will receive an application key (rhk_...) and a secret (rhs_...). The secret is shown once, so store it somewhere safe.

Add both to your configuration:

// config/hub.php

return [
    'url'    => env('HUB_URL', 'https://realtimehub.raheelshan.com'),
    'key'    => env('HUB_KEY'),
    'secret' => env('HUB_SECRET'),
];

Now create a route that exchanges the authenticated Laravel user for a hub token:

// routes/web.php

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');

Notice where userId comes from. It comes from the authenticated Laravel session, not from a request parameter. Never allow the browser to choose its own user ID here. Otherwise, one user could request a token pretending to be someone else.

The token is valid for one hour by default.

Setup: the browser

The browser uses the SignalR client and a small RealtimeHub SDK.

<script src="https://cdn.jsdelivr.net/npm/@microsoft/[email protected]/dist/browser/signalr.min.js"></script>

<script type="module">
import { createRealtimeClient } from 'https://realtimehub.raheelshan.com/sdk/realtimehub-client.js';

const client = createRealtimeClient({
    hubUrl: 'https://realtimehub.raheelshan.com/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();

await client.send('bob', 'chat', {
    text: 'hello'
});
</script>

The API should look familiar if you have worked with SignalR:

  • start() opens the connection.
  • send(userId, event, payload) sends a message through the connection, using the hub's invocation mechanism.
  • onEvent handles incoming messages, similar to a ReceiveMessage handler.

The send() method resolves with a message ID and a persisted flag. If the hub rejects the message, the promise rejects, so the browser can handle the error instead of assuming everything worked.

Getting client messages into Laravel: the alternatives

Before settling on a webhook, I considered other ways to get messages from SignalR into my application.

The important thing to understand is that SignalR can already deliver a message directly from one connected client to another. Saving that message is a separate responsibility.

The flow does not have to be:

Browser A
    |
    v
SignalR
    |
    v
Laravel
    |
    v
Database
    |
    v
SignalR
    |
    v
Browser B

That design would put Laravel in the middle of every message. It would receive the message, save it, and then broadcast it again. That is not necessarily how SignalR communication works, and it is not the flow I wanted.

There are several ways to handle persistence without making Laravel the relay for every live message.

Option 1: Run a long-running listener

One possibility is to create another application process that connects to the SignalR hub and listens for events. The hub would deliver or broadcast the relevant event to that listener. The listener could then pass the data to Laravel or save it through an application endpoint.

Browser A
    |
    | Send message
    v
SignalR Hub
    |
    +--------------------> Browser B
    |
    +--------------------> Long-running listener
                                  |
                                  v
                              Laravel
                                  |
                                  v
                               Database

The direct message from Browser A to Browser B still works. The listener is a separate consumer of the event, not a mandatory middleman between the two browsers.

This approach has an operational cost. The listener must stay connected, reconnect when the connection drops, and handle failures without losing messages. You also need to make sure the hub actually sends the relevant events to that listener. A SignalR client cannot automatically observe every message just because it connects to the hub; the hub needs to expose and deliver those events to it.

It is possible, but it brings back the long-running-process responsibility I had already met with the Redis subscriber in Article 4.

Option 2: Build and host your own ASP.NET Core SignalR application

Another option is to build the SignalR application using ASP.NET Core and run it on the same server as the Laravel application. The ASP.NET Core application can have direct access to the database. Its hub method can save an incoming message and send it to the intended recipient.

Browser A
    |
    | Invoke hub method
    v
ASP.NET Core SignalR Hub
    |
    +--------------------> Save message to database
    |
    +--------------------> Browser B

This is a natural approach when you own the SignalR application and want the hub itself to handle persistence.

But it introduces another backend application. Your Laravel application and ASP.NET Core application now need to agree on authentication, database access, and application rules. Running them on the same server does not make those responsibilities disappear.

It is a valid architecture, especially if you are comfortable maintaining both applications. It just was not the setup I wanted for this project.

Option 3: Use a webhook

This is the approach I chose for RealtimeHub.

The browser sends a message through its SignalR connection. The hub handles delivery to the recipient and separately forwards the message to Laravel through a webhook.

Browser A
    |
    | Send message
    v
RealtimeHub
    |
    +--------------------> Browser B
    |
    +--------------------> Webhook
                                  |
                                  v
                               Laravel
                                  |
                                  v
                               Database

Notice that Laravel is not sitting between the sender and recipient. The hub can deliver the message directly to Browser B. Laravel receives a separate notification so it can save the message and apply its own application logic.

This separation is intentional. If Laravel is temporarily unavailable, the hub can still handle live delivery, while the webhook delivery mechanism retries the persistence notification according to its configured policy.

Setup: configure the webhook

In the dashboard, open the Persistence tab, enter your webhook URL, and enable the webhook. The dashboard provides a signing secret.

Now install the Laravel package:

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

Add the webhook secret to your .env file:

REALTIMEHUB_WEBHOOK_SECRET=the-signing-secret

The package verifies the webhook signature and fires a Laravel event. You can listen for that event like any other Laravel event. For example:

// app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Event;
use Ohad\RealtimeHub\Events\RealtimeEventReceived;

public function boot(): void
{
    Event::listen(RealtimeEventReceived::class, function ($e) {
        match ($e->eventName) {
            'chat' => \App\Models\Message::firstOrCreate(
                ['hub_event_id' => $e->eventId],
                [
                    'from' => $e->from,
                    'to' => $e->to,
                    'text' => $e->payload['text'],
                ],
            ),

            default => null,
        };
    });
}

The browser sends a message through the WebSocket connection. The hub forwards it to Laravel, and Laravel creates a database record. No second HTTP request from the browser. No Redis subscriber. No custom Artisan command.

There is another important detail: $e->eventId remains stable when the hub retries delivery. Using it as the unique lookup key makes the listener idempotent. If Laravel receives the same event again, firstOrCreate() avoids creating another message record.

The package also saves incoming messages to a realtime_events table by default.

What happens if your server is down?

A webhook is only useful if it can handle temporary failures. The hub is designed to retry delivery when your Laravel endpoint is unavailable:

  • Messages are delivered in batches of up to 50.
  • Failed requests are retried after 30 seconds, 2 minutes, 10 minutes, and 30 minutes.
  • After the retry attempts, messages are set aside.
  • Delivery is at-least-once, not exactly-once.
  • The hub holds approximately 10,000 messages per application while the webhook is unavailable.

This is why the Laravel listener must be safe to execute more than once.

Compare this with the whisper listener from Article 2. If that process crashed while a message was being sent, the message could disappear without ever reaching your application. Here, the hub manages webhook delivery and retries.

Sending messages from Laravel

Communication does not have to start from the browser. Your Laravel application can also send messages to connected users:

use Ohad\RealtimeHub\Facades\RealtimeHub;

RealtimeHub::send(
    $order->user_id,
    'notification',
    ['text' => 'Your order shipped']
);

RealtimeHub::send(
    [$a->id, $b->id],
    'notification',
    ['text' => 'New comment']
);

The browser receives these messages through onEvent. Server-originated messages have from set to $server.

They are not saved and are not forwarded to the webhook. Your Laravel application already knows what it sent, so forwarding the same message back to itself would serve no purpose.

Channels

For group communication, you can use channels. A channel is a room with a name you define, such as room.5. The browser joins the channel, and your server can broadcast to everyone in it with one call:

RealtimeHub::broadcast(
    'room.5',
    'room.message',
    ['text' => 'Hello room']
);

A channel message counts as one message regardless of how many connected users receive it.

There are two important limitations:

  • Channel messages are not saved.
  • Channel messages are not forwarded to your webhook.

If a channel message must be stored in your database, it needs to go through a Laravel endpoint first. I will cover that approach in Article 6, along with controlling who can join a channel.

Validate messages before they spread

Accepting arbitrary payloads from connected browsers is not a good idea. You can define a JSON Schema for each event name:

{
    "type": "object",
    "required": ["text"],
    "properties": {
        "text": {
            "type": "string",
            "minLength": 1,
            "maxLength": 500
        },
        "replyTo": {
            "type": "string"
        }
    },
    "additionalProperties": false
}

The hub validates messages against the schema before delivery. In strict mode, event names that have not been declared are rejected. That means an invalid payload is rejected before it reaches the other user or your Laravel webhook.

What it does not do

Before choosing a hosted hub, understand its limitations.

  • Channel messages are not saved. Messages sent to channels are neither stored nor forwarded to your webhook. If you need to retain them, send them through a Laravel endpoint first.
  • Channels are small rooms. A connection can join at most 20 channels, and a token can list at most 50. Presence is held in the memory of one hub server. I will cover the implications in Article 7.
  • You cannot remove a member from a live connection. If you remove a user from your application's permissions, an already connected user continues receiving messages until they disconnect.
  • There is no offline delivery. If a user is disconnected when a message is sent, they will not receive it later. Load message history from your own database when they reconnect. The webhook is what lets you build that history for one-to-one messages.
  • It is a hosted dependency. The hub runs at a URL you do not control from your own server. You are relying on an external service for the live connection.
  • There are usage limits. 3 applications per account, 1,000 open connections per application, 100 messages per second per application, 10 messages per second per connection, and a 32 KB maximum payload.

For notifications, direct messages, support chat, order tracking, and live status updates between known users, these limits may be sufficient. For large public rooms with thousands of members, Reverb is a more suitable option to consider.

The final count

Article 1 started with seven moving parts. This is where the stack stands now:

  1. A Laravel application with a token route.
  2. A browser client connected directly to the hosted hub.
  3. A webhook endpoint handled by the Laravel package.

No queue worker for broadcasting. No socket server to maintain. No Redis. No Laravel Echo.

I started with a paid option, moved to free options that I had to host myself, and eventually built a setup where I host nothing for the WebSocket connection.

That journey cost me quite a few hours. Apparently, learning real-time communication is mostly learning how many different processes can stop working independently.

Try it: RealtimeHub documentation

Previous: How I Made Laravel Receive Browser Messages With WebSockets and Redis

Next: Real-Time Chat Rooms in Laravel: Control Who Joins and Who Posts

Comment "HUB" and I'll send you the token route and webhook listener as a copy-paste starter.

Found this useful?

Support the work that goes into these posts.

Support
Comments


Comment created and will be displayed once approved.