DEV Community

vimuth
vimuth

Posted on • Edited on

Building a Simple Laravel App with Reverb: A Step-by-Step Guide

Laravel is a powerful PHP framework known for its elegant syntax and developer-friendly features. Reverb, Laravel’s real-time event broadcasting system, makes it easy to integrate live updates into your applications. In this guide, we’ll walk through building a simple Laravel app with Reverb, showing how to set up real-time functionality step by step. Whether you're new to Laravel or looking to explore real-time features, this tutorial will help you get started quickly.

Install laravel

First let's install laravel.

composer create-project --prefer-dist laravel/laravel reverbapp

And inside reverbapp folder add php artisan serve and test the app.

Image description

Install Reverb

Let's install reverb. Give yes to all prompts appear. They will install reverb PHP packages and Node packages like echo and pusher-js

php artisan install:broadcasting
Enter fullscreen mode Exit fullscreen mode

Now you can see inside .env these settings.

BROADCAST_CONNECTION=reverb
REVERB_APP_ID=981064
REVERB_APP_KEY=oi4rnynjhmgd5vvz024v
REVERB_APP_SECRET=uxtmtcqs30kh2vcqpt58
REVERB_HOST="localhost"
REVERB_PORT=8080
REVERB_SCHEME=http

VITE_REVERB_APP_KEY="${REVERB_APP_KEY}"
VITE_REVERB_HOST="${REVERB_HOST}"
VITE_REVERB_PORT="${REVERB_PORT}"
VITE_REVERB_SCHEME="${REVERB_SCHEME}"

Enter fullscreen mode Exit fullscreen mode

Building the App

Lets create the event

php artisan make:event MessageSent
Enter fullscreen mode Exit fullscreen mode

We'll modify this event to broadcast a simple $message object via 'public-messages' public channel. Here is the code

<?php

namespace App\Events;

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

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

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    // Broadcast via public channel
    public function broadcastOn()
    {
        return new Channel('public-messages');
    }

    public function broadcastAs()
    {
        return 'message.sent';
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's create two routes and a view in Laravel:

  • One route to send data
  • One route with a view to receive data

This is send route

use Illuminate\Support\Facades\Route;
use App\Events\MessageSent;

Route::get('/send-message', function () {
    // Sending a simple object instead of a model
    $message = [
        'user' => 'John Doe',
        'text' => 'Hello from Laravel Reverb!',
        'timestamp' => now()->toDateTimeString(),
    ];

    // Fire the event
    broadcast(new MessageSent($message));

    return response()->json(['status' => 'Message broadcasted!']);
});
Enter fullscreen mode Exit fullscreen mode

This is revive route.

Route::get('/receive-data', function () {
    return view('receive');
});
Enter fullscreen mode Exit fullscreen mode

And view

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reverb Broadcast</title>
    @vite(['resources/js/app.js']) {{-- Load JS --}}
</head>
<body>
    <h1>Listening for Messages...</h1>
    <pre id="output"></pre>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            window.Echo.channel("public-messages")
                .listen(".message.sent", (event) => {
                    console.log("Received:", event);
                    document.getElementById("output").textContent = JSON.stringify(event, null, 2);
                });
        });
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And you need to run npm run dev or npm run build to allow window.Echo

Combining with reverb

First let's start reverb server. Run this command in different cli

php artisan reverb:start
Enter fullscreen mode Exit fullscreen mode

Now you can see websocket connection is made

Image description

But you need to open a new window and also the run this command for processing jobs that are queued for execution in the background.

php artisan queue:work
Enter fullscreen mode Exit fullscreen mode

That is it. When you insert 'http://localhost:8000/send-message' in window you will see this in another window

And receive it from 'http://localhost:8000/receive-data'

Image description

Let's meet with another post about how to deploy this to server.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
arif98741 profile image
Ariful Islam

Thanks for nice article. I also have created another article, if anyone wants, he/she can go through it
Laravel Reverb Install for Realtime Notification for Laravel 11

Collapse
 
vimuth7 profile image
vimuth

Thanks for sharing mate. Nice work

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay