Tuesday, 25 February 2025

What is Laravel Reverb?

Laravel Reverb is a built-in WebSocket server introduced in Laravel 11 that allows you to create real-time applications without needing third-party services like Pusher or Laravel WebSockets.

πŸ”₯ In short: Laravel Reverb makes it easy to implement WebSockets in Laravel without any extra setup or costs.


πŸ“Œ Why use Laravel Reverb?

No need for Pusher → Reduces costs, no third-party dependencies.
Built into Laravel 11 → No need to install Laravel WebSockets.
High performance → Optimized for Laravel applications.
Easy to configure & deploy → Runs as a service within Laravel.


πŸ”§ How to Use Laravel Reverb?

1️⃣ Enable Reverb in Laravel

Open your .env file and set the broadcast driver to reverb:

env
BROADCAST_DRIVER=reverb

Start the Reverb WebSocket server with:

sh
php artisan reverb:start

By default, Reverb runs on port 6001.


2️⃣ Create an Event for Broadcasting Messages

πŸ“Œ Generate a new event:

sh
php artisan make:event MessageSent

πŸ“Œ Edit app/Events/MessageSent.php:

php
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class MessageSent implements ShouldBroadcast { use InteractsWithSockets, SerializesModels; public $message; public function __construct($message) { $this->message = $message; } public function broadcastOn() { return new Channel('chat'); } }

πŸ“Œ Explanation:

  • This event broadcasts on the chat channel.
  • When a message is sent, all clients listening to this channel will receive the event in real-time.

3️⃣ Update the Controller to Send Messages

πŸ“Œ Create ChatController:

sh
php artisan make:controller ChatController

πŸ“Œ Modify app/Http/Controllers/ChatController.php:

php
use Illuminate\Http\Request; use App\Events\MessageSent; class ChatController extends Controller { public function sendMessage(Request $request) { $message = [ 'user' => auth()->user()->name, 'message' => $request->message, ]; broadcast(new MessageSent($message))->toOthers(); return response()->json(['message' => $message]); } }

πŸ“Œ Explanation:

  • When a user sends a message, it broadcasts (broadcast()) the MessageSent event over WebSockets.

4️⃣ Add API Routes for Chat

πŸ“Œ Open routes/api.php and add:

php
use App\Http\Controllers\ChatController; Route::middleware('auth:sanctum')->post('/send-message', [ChatController::class, 'sendMessage']);

πŸ“Œ Now, the API will send messages in real-time!


5️⃣ Set Up Laravel Echo on Frontend

πŸ“Œ Install Laravel Echo & Reverb Client:

sh
npm install --save laravel-echo @laravel/reverb

πŸ“Œ Open resources/js/bootstrap.js and update:

js
import Echo from 'laravel-echo'; import Reverb from '@laravel/reverb'; window.Echo = new Echo({ broadcaster: Reverb, host: 'http://localhost:6001', }); window.Echo.channel('chat') .listen('MessageSent', (event) => { console.log("New message:", event.message); });

πŸ“Œ Explanation:

  • window.Echo.channel('chat') → Listens for the MessageSent event on the chat channel.
  • When a new message is received, it will log the message to the console.

πŸ“Œ Rebuild the frontend assets:

sh
npm run dev

6️⃣ Start WebSocket and Test Chat

πŸ“Œ Run Laravel server:

sh
php artisan serve

πŸ“Œ Start Laravel Reverb WebSocket:

sh
php artisan reverb:start

πŸ“Œ Send a message via API:

sh
curl -X POST "http://127.0.0.1:8000/api/send-message" -H "Authorization: Bearer YOUR_ACCESS_TOKEN" -H "Content-Type: application/json" -d '{"message":"Hello, world!"}'

πŸ“Œ If successful, the frontend console should display the message in real-time! πŸŽ‰


🎯 Summary

Laravel Reverb allows you to implement WebSockets without needing Pusher.
Simple setup—just start with php artisan reverb:start.
Works seamlessly with Laravel Echo for real-time events.
Integrates easily with Vue.js, React, or Blade templates.

πŸ‘‰ Now you have a real-time chat system in Laravel 11 without using any third-party services! πŸš€


Integrating Laravel Reverb with Vue 3 + TypeScript for Real-time Chat

Since you're using Vue 3 with TypeScript, you'll need to set up Laravel Echo with Reverb in Vue properly.


πŸ›  1. Install Dependencies

In your Vue 3 project, install Laravel Echo and Reverb client:

sh
npm install --save laravel-echo @laravel/reverb

πŸ“Œ 2. Set Up Laravel Echo in Vue 3 (TypeScript)

Create a new file src/utils/reverb.ts to handle WebSocket connections:

ts
import Echo from 'laravel-echo'; import Reverb from '@laravel/reverb'; declare global { interface Window { Echo: Echo; } } // Initialize Laravel Echo with Reverb window.Echo = new Echo({ broadcaster: Reverb, host: 'http://localhost:6001', // Ensure this matches your Laravel Reverb server }); export default window.Echo;

πŸ“Œ 3. Implement Chat Component in Vue 3

Create a new component src/components/Chat.vue:

vue
<script setup lang="ts"> import { ref, onMounted, onUnmounted } from 'vue'; import Echo from '@/utils/reverb'; import axios from 'axios'; interface Message { user: string; message: string; } const messages = ref<Message[]>([]); const newMessage = ref(''); const fetchMessages = async () => { try { const response = await axios.get<Message[]>('http://127.0.0.1:8000/api/messages', { headers: { Authorization: `Bearer YOUR_ACCESS_TOKEN` }, }); messages.value = response.data; } catch (error) { console.error('Error fetching messages:', error); } }; const sendMessage = async () => { if (!newMessage.value.trim()) return; try { await axios.post( 'http://127.0.0.1:8000/api/send-message', { message: newMessage.value }, { headers: { Authorization: `Bearer YOUR_ACCESS_TOKEN` } } ); newMessage.value = ''; // Clear input after sending } catch (error) { console.error('Error sending message:', error); } }; onMounted(() => { fetchMessages(); Echo.channel('chat') .listen('MessageSent', (event: { message: Message }) => { messages.value.push(event.message); }); }); onUnmounted(() => { Echo.leave('chat'); // Cleanup WebSocket connection }); </script> <template> <div class="chat-container"> <div class="messages"> <div v-for="(msg, index) in messages" :key="index" class="message"> <strong>{{ msg.user }}</strong>: {{ msg.message }} </div> </div> <div class="input-box"> <input v-model="newMessage" placeholder="Type a message..." @keyup.enter="sendMessage" /> <button @click="sendMessage">Send</button> </div> </div> </template> <style scoped> .chat-container { width: 400px; border: 1px solid #ddd; padding: 10px; border-radius: 5px; } .messages { max-height: 300px; overflow-y: auto; margin-bottom: 10px; } .message { padding: 5px; border-bottom: 1px solid #ddd; } .input-box { display: flex; gap: 10px; } input { flex: 1; padding: 5px; } button { padding: 5px 10px; cursor: pointer; } </style>

πŸ“‘ 4. Update Laravel Backend

Make sure you have these APIs in Laravel 11:

πŸ“Œ Modify routes/api.php:

php
use App\Http\Controllers\ChatController; Route::middleware('auth:sanctum')->group(function () { Route::post('/send-message', [ChatController::class, 'sendMessage']); Route::get('/messages', [ChatController::class, 'getMessages']); });

πŸ“Œ Modify app/Http/Controllers/ChatController.php:

php
use Illuminate\Http\Request; use App\Models\Message; use App\Events\MessageSent; class ChatController extends Controller { public function sendMessage(Request $request) { $message = Message::create([ 'user_id' => auth()->id(), 'message' => $request->message, ]); broadcast(new MessageSent($message))->toOthers(); return response()->json(['message' => $message]); } public function getMessages() { return Message::with('user')->latest()->take(50)->get(); } }

πŸ“Œ Modify app/Events/MessageSent.php:

php
use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use App\Models\Message; class MessageSent implements ShouldBroadcast { use InteractsWithSockets, SerializesModels; public $message; public function __construct(Message $message) { $this->message = $message; } public function broadcastOn() { return new Channel('chat'); } }

πŸ”₯ 5. Start the Application

Run Laravel server:

sh
php artisan serve

Start Laravel Reverb WebSocket:

sh
php artisan reverb:start

Run Vue frontend:

sh
npm run dev

🎯 Summary

Laravel 11 Backend

  • Uses Laravel Reverb instead of Pusher.
  • API for sending & fetching messages.
  • Broadcasts messages using Laravel Echo.

Vue 3 + TypeScript Frontend

  • Uses Laravel Echo with Reverb for real-time messaging.
  • Listens for events and updates the chat UI.
  • API calls for sending & receiving messages.

πŸš€ Now you have a real-time chat system with Laravel Reverb + Vue 3 + TypeScript! πŸŽ‰

Thank you

No comments:

Post a Comment

Golang Advanced Interview Q&A