This website is currently under active development (Beta) 🚀. Some features are still work in progress.
Tutorials Tutorial

Unlocking Real-time: A Comprehensive Guide to Laravel Reverb

Admin User
Admin User
Sep 05, 2026
5 min read

Key Takeaways

  • # Unlocking Real-time: A Comprehensive Guide to Laravel Reverb
  • Laravel Reverb is a powerful, first-party WebSocket server for Laravel applications, designed to...

Unlocking Real-time: A Comprehensive Guide to Laravel Reverb #

Laravel Reverb is a powerful, first-party WebSocket server for Laravel applications, designed to make real-time features like live chat, notifications, and interactive dashboards easier than ever. Built on top of WebSockets, Reverb offers a performant, scalable, and self-hosted solution, freeing developers from relying solely on third-party services like Pusher or Ably.

In this detailed tutorial, we'll walk through setting up Laravel Reverb in your application, broadcasting events, and listening for them on the frontend using Laravel Echo.

Why Laravel Reverb? #

Before Reverb, Laravel's broadcasting capabilities primarily relied on external services. While effective, these services often introduced additional costs, configuration complexities, and external dependencies. Reverb changes this by providing:

  • Self-Hosting: Full control over your real-time infrastructure.
  • Performance: Optimized for speed and efficiency, leveraging native WebSockets.
  • Scalability: Designed to handle a high volume of connections and messages.
  • Simplicity: Seamless integration with Laravel's existing broadcasting system.
  • Cost-Effectiveness: Eliminates recurring subscription fees for real-time services.

Prerequisites #

To follow along with this tutorial, you'll need:

  • A fresh or existing Laravel 10.x (or higher) application.
  • PHP 8.2 or higher.
  • Composer installed.
  • Node.js and NPM/Yarn installed.

Step 1: Installation and Configuration #

First, let's install Laravel Reverb via Composer:

composer require laravel/reverb

After installation, publish Reverb's configuration file:

php artisan reverb:install

This command will publish config/reverb.php and update your .env file with essential Reverb variables.

Step 2: Configure Environment Variables #

Open your .env file and ensure the following variables are set correctly. Reverb automatically populates these during reverb:install, but it's good to review them.

BROADCAST_CONNECTION=reverb

REVERB_APP_ID=your-app-id
REVERB_APP_KEY=your-app-key
REVERB_APP_SECRET=your-app-secret
REVERB_HOST="0.0.0.0" # Or your public IP if accessing from external
REVERB_PORT=8080
REVERB_SCHEME=http # Use https if you have SSL setup for Reverb
REVERB_TLS_CERTIFICATE=""
REVERB_TLS_KEY=""
REVERB_TLS_PASSPHRASE=""
  • REVERB_APP_ID, REVERB_APP_KEY, REVERB_APP_SECRET: These are unique credentials generated for your application.
  • REVERB_HOST: 0.0.0.0 allows Reverb to listen on all available network interfaces. For local development, 127.0.0.1 or localhost might be sufficient. For production, use your server's public IP or domain.
  • REVERB_PORT: The port Reverb will listen on. 8080 is common.
  • REVERB_SCHEME: Set to https if you're serving Reverb over SSL (highly recommended for production). You'll also need to configure REVERB_TLS_CERTIFICATE and REVERB_TLS_KEY.

Step 3: Frontend Setup with Laravel Echo #

On the frontend, Laravel Echo is used to subscribe to channels and listen for events. You'll need laravel-echo and pusher-js (which Reverb uses internally for its client-side protocol).

npm install laravel-echo pusher-js
# or
yarn add laravel-echo pusher-js

Next, configure Laravel Echo in your resources/js/bootstrap.js (or similar entry point). Make sure to uncomment and adjust the Echo configuration block:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'reverb', // Changed from 'pusher' to 'reverb'
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT ?? 8080,
    wssPort: import.meta.env.VITE_REVERB_PORT ?? 8080,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});

You'll also need to expose the Reverb environment variables to your frontend. Update your .env file with VITE_ prefixes:

VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}" # e.g., http or https

Remember to run npm run dev (or npm run build for production) to compile your assets after these changes.

Step 4: Starting the Reverb Server #

With everything configured, you can now start the Reverb server:

php artisan reverb:start

For production environments, you should use a process manager like Supervisor to keep Reverb running and restart it automatically if it crashes.

Step 5: Broadcasting Events from Backend #

To send real-time data from your Laravel backend, you'll use broadcastable events.

Create a Broadcastable Event #

Generate a new event:

php artisan make:event MessageSent

Open app/Events/MessageSent.php and implement the ShouldBroadcast interface. Define the data you want to broadcast and the channel(s) it should be sent to.

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class MessageSent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $username;
    public $message;

    /**
     * Create a new event instance.
     */
    public function __construct(string $username, string $message)
    {
        $this->username = $username;
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new Channel('chat'), // Public channel
            // new PrivateChannel('user.'.$this->userId), // Private channel for specific users
        ];
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs(): string
    {
        return 'message.sent';
    }

    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith(): array
    {
        return [
            'username' => $this->username,
            'message' => $this->message,
            'timestamp' => now()->toDateTimeString(),
        ];
    }
}
  • broadcastOn(): Defines the channels. Channel for public, PrivateChannel for authenticated users.
  • broadcastAs(): Customizes the event name on the frontend (defaults to event class name).
  • broadcastWith(): Specifies the data payload sent with the event.

Trigger the Event #

You can trigger this event from a controller, service, or wherever appropriate:

<?php

namespace App\Http\Controllers;

use App\Events\MessageSent;
use Illuminate\Http\Request;

class ChatController extends Controller
{
    public function sendMessage(Request $request)
    {
        $username = $request->input('username', 'Guest');
        $message = $request->input('message');

        event(new MessageSent($username, $message));

        return response()->json(['status' => 'Message sent!']);
    }
}

Make sure you have a route defined for this controller method:

// routes/web.php or routes/api.php
Route::post('/send-message', [ChatController::class, 'sendMessage']);

Step 6: Listening for Events on Frontend #

Now, let's listen for the message.sent event on the chat channel using Laravel Echo. You can add this to your resources/js/app.js or a specific Vue/React component.

// resources/js/app.js or a component script

// Listen for public channel events
window.Echo.channel('chat')
    .listen('.message.sent', (e) => { // Note the leading dot for broadcastAs()
        console.log('New message:', e.username, e.message, e.timestamp);
        // Add logic to display the message in your UI
        const messagesDiv = document.getElementById('messages');
        if (messagesDiv) {
            const newMessage = document.createElement('p');
            newMessage.textContent = `${e.username} (${e.timestamp}): ${e.message}`;
            messagesDiv.appendChild(newMessage);
        }
    });

// If using private channels, ensure authentication middleware is setup on backend
// and use:
// window.Echo.private('user.1')
//     .listen('MessageSent', (e) => {
//         console.log('Private message for user 1:', e);
//     });

console.log('Listening for chat messages...');

Important: If you used broadcastAs() in your event, remember to prepend a . (dot) to the event name when listening on the frontend (e.g., .message.sent). If you didn't use broadcastAs(), listen directly to the class name (e.g., 'MessageSent').

Advanced Configuration & Scaling #

Reverb's config/reverb.php file offers various configuration options:

  • apps: Define multiple applications with different keys/secrets.
  • pulses: Configure health checks and heartbeats.
  • webhooks: Send webhooks to your application for events like channel subscription/unsubscription.
  • scaling: Reverb supports Redis for horizontal scaling across multiple Reverb instances. This is crucial for high-traffic applications. To enable it, ensure you have Redis installed and configured, then uncomment the scaling section in reverb.php and set enabled to true.

Conclusion #

Laravel Reverb provides a robust, integrated solution for adding real-time capabilities to your Laravel applications. By self-hosting your WebSocket server, you gain more control, potentially reduce costs, and streamline your development workflow. Embrace Reverb to build more dynamic and interactive user experiences with the power of Laravel!

FAQs

What is Laravel Reverb and why should I use it?
Laravel Reverb is a first-party, self-hosted WebSocket server that integrates seamlessly with Laravel's broadcasting features. You should use it to build real-time applications (like chat, notifications) without relying on external services, offering more control, better performance, and cost savings.
How do I scale Laravel Reverb for high-traffic applications?
For horizontal scaling, Laravel Reverb can be configured to use Redis. By enabling the `scaling` option in the `config/reverb.php` file and ensuring Redis is properly set up, you can run multiple Reverb instances and distribute connections across them.

Want more content like this?

Explore more tutorials in the Tutorials section.

Explore Tutorials

You might also like