#

Going Real-Time with Reverb – Laravel Tutorial

 


Going Real-Time with Reverb – Laravel Tutorial

1. Install Laravel Project

Create a new project.

composer create-project laravel/laravel realtime-app
cd realtime-app

Run the server:

php artisan serve

2. Install Reverb (WebSocket Server)

Install broadcasting and Reverb.

php artisan install:broadcasting

During installation select Reverb.

This installs:

  • Reverb server

  • Broadcasting config

  • WebSocket setup

Install npm packages:

npm install
npm run dev

Start Reverb server:

php artisan reverb:start

3. Configure Broadcasting

Open .env

BROADCAST_DRIVER=reverb

Example Reverb config:

REVERB_APP_ID=local
REVERB_APP_KEY=local
REVERB_APP_SECRET=local
REVERB_HOST=127.0.0.1
REVERB_PORT=8080

4. Create Broadcast Event

Create an event:

php artisan make:event MessageSent

Edit the event.

use Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessageSent implements ShouldBroadcast
{
public $message;

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

public function broadcastOn()
{
return new Channel('chat');
}
}

This event will broadcast data to chat channel.


5. Create Route to Send Message

Open routes/web.php.

use App\Events\MessageSent;

Route::post('/send-message', function () {

$message = request('message');

broadcast(new MessageSent($message));

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

6. Install Echo for Frontend

Install Laravel Echo.

npm install laravel-echo pusher-js

Edit resources/js/bootstrap.js

import Echo from "laravel-echo";

window.Echo = new Echo({
broadcaster: "reverb",
host: window.location.hostname + ":8080",
});

7. Listen for Real-Time Events

Example frontend code:

Echo.channel("chat")
.listen("MessageSent", (e) => {
console.log("New message:", e.message);
});

Now when a message is sent, it appears instantly.


8. Simple Chat UI Example

Example HTML:

<input id="message" type="text">
<button onclick="sendMessage()">Send</button>

<ul id="chat"></ul>

Javascript:

function sendMessage() {

fetch("/send-message", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({
message: document.getElementById("message").value
})
});

}

Echo.channel("chat")
.listen("MessageSent", (e) => {

let li = document.createElement("li");
li.innerText = e.message;

document.getElementById("chat").appendChild(li);

});

Messages will appear instantly without page refresh.


Real-World Uses of Reverb

You can build:

  • 💬 Live chat

  • 🔔 Notifications

  • 📊 Real-time dashboards

  • 👥 Online users

  • 📦 Order status updates

  • 🎮 Multiplayer games


Why Use Reverb Instead of Pusher?

Advantages:

  • Free

  • Self-hosted

  • Built for Laravel

  • No third-party service required

Post a Comment

Previous Post Next Post