Laravel Reverb stands out as a powerful solution for enhancing the development workflow and improving developer productivity.
Laravel Reverb is a first-party WebSocket server for Laravel applications, providing real-time communication capabilities between the client and server seamlessly.

This blog post will explore Laravel Reverb’s use cases and benefits for Laravel developers.

What is Laravel Reverb?

  • Laravel Reverb is a groundbreaking WebSocket server developed by the Laravel team and designed to integrate real-time communication capabilities seamlessly into Laravel applications. Laravel Reverb allows developers to build interactive, dynamic, and engaging web applications by enabling direct and instantaneous communication between the client and server.

Main Features of Laravel Reverb

  • Integration with Laravel Echo
    • Laravel Reverb uses Pusher Protocol to seamlessly integrate with Laravel Echo, a JavaScript library for subscribing to real-time events broadcast by Laravel applications. Developers can use Laravel Echo to subscribe to WebSocket channels and receive real-time updates in the browser, enabling interactive and dynamic user experiences.
  • Seamless Integration
    • Laravel Reverb is designed to work seamlessly with Laravel’s broadcasting capabilities, making it easy to deploy with Laravel Forge integration. This integration ensures that developers can easily subscribe to channels and listen for events, unlocking the full potential of Laravel in broadcasting events
  • Blazing Fast
    • Laravel Reverb is designed to provide exceptional performance, making it a top choice for developers seeking speed and efficiency in their web applications. This speed is achieved through various optimizations within the Laravel framework, including efficient routing, caching mechanisms, and optimized database queries. Additionally, Laravel Reverb leverages modern PHP features and incorporates best practices to minimize overhead and maximize execution speed.
  • Built to Scale
    • By leveraging Redis and its built-in support for horizontal scaling, Laravel Reverb enables developers to infinitely increase the capacity of their applications while maintaining high performance and reliability. This makes it well-suited for handling the demands of large-scale, high-traffic web applications that need to scale dynamically based on user demand.
  • Exceptional Speed
    • Laravel Reverb is optimized for speed, allowing a single server to support thousands of connections and pipe data without delay. This ensures a responsive user experience and enhances the overall performance of the application
  • Pusher Protocol
    • Laravel Reverb utilizes the Laravel Pusher protocol for WebSockets, making it immediately compatible with Laravel Broadcasting and Laravel Echo. This ensures that developers can easily implement real-time communication in Laravel applications

Usecase of Laravel Reverb

  • Based on the features and capabilities of Laravel Reverb, some best practices and use cases can be inferred:
    • Optimizing Performance:
      • Utilize Reverb’s blazing-fast speed by optimizing data transfer and minimizing unnecessary operations.
    • Scalability Planning
      • Leverage Reverb’s built-in support for horizontal scaling to plan for the seamless expansion of real-time features as the application grows.
    • Monitoring and Maintenance
      • Take advantage of Reverb’s baked-in support for Pulse to monitor real-time communication and ensure smooth operation.

Use Cases

  • Real-Time Collaboration
    • Implement real-time editing and collaboration features in content management systems or document editing applications.
  • Live Customer Support
    • Enable real-time chat and support features for immediate customer assistance.
  • Live Data Visualization
    • Develop real-time dashboards for monitoring system performance, IoT devices, or financial data.

Using the below steps integrate reverb :

  • Installing Laravel project with the latest version 11
    • composer create-project laravel/laravel reverb-demo
  • Configure database.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-reverb
DB_USERNAME=root
DB_PASSWORD=
  • If the node js is not installed then install the node js
  • You may install Reverb using the below artisan command
    • php artisan install:broadcasting
    • Behind the install:broadcasting Artisan command will run the reverb:install command, which will install Reverb with a sensible set of default configuration options. If you would like to make any configuration changes, you may do so by updating Reverb’s environment variables or by updating the config/reverb.php configuration file.
  • Just enter to continue this script.
  • Just enter to continue this script.
  • After the install:broadcasting command automatically generated an echo.js file inside the resource/js folder.
  • echo.js file example
import Echo from 'laravel-echo';

import Pusher from 'pusher-js';
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: 'reverb',
    key: import.meta.env.VITE_REVERB_APP_KEY,
    wsHost: import.meta.env.VITE_REVERB_HOST,
    wsPort: import.meta.env.VITE_REVERB_PORT ?? 80,
    wssPort: import.meta.env.VITE_REVERB_PORT ?? 443,
    forceTLS: (import.meta.env.VITE_REVERB_SCHEME ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
});
  • Add echo.js file into the resource/js/app.js file
import './bootstrap';
import './echo';
  • Set Up a Laravel Event using the below command
    • php artisan make:event SendMessage
<?php

namespace App\Events;

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

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

    private $chatData;

    /**
     * sendMessage constructor.
     * @param $chatData
     */
    public function __construct($chatData)
    {
        $this->chatData = $chatData;
    }

    /**
     * @return array
     */
    public function broadcastWith()
    {
        return ['chat' => $this->chatData];
    }

    /**
     * @return string
     */
    public function broadcastAs()
    {
        return 'getChatMessage';
    }

    /**
     * @return PrivateChannel[]
     */
    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('chat-message'),
        ];
    }
}
  • Call the above event in the controller after you store chat data in the database.
  • event( new SendMessage($addMessage)); In the $addMessage send an object after data is stored in the chat table.
  • On clicking the send button using the below code store message data using Ajax call and call event listener to show a message to another user.
$(document).on('click', '.send-button', function(e) {
            const message = {
                "_token": "{{ csrf_token() }}",
                sender_id: $(".sender_id").val(),
                receiver_id: receiver_id,
                message: $(".message-box").val(),
            };
            $.ajax({
                url: '{{ route('chat.send') }}',
                type: 'post',
                data: message,
                success: function(response){
                    if(response.status == 200)
                    var messageData = '<li class="self">\n' +
                            '              <div class="msg">\n' +
                                '              <p>'+ response.data.message+'</p>\n' +
                                '              <time>'+ response.data.created_at+'</time>\n' +
                            '               </div>';
                            '          </li>';
                    $('.message-box').val('')
                    $('.chat').append(messageData)
                }
            });
        });
        document.addEventListener('DOMContentLoaded', function () {
            Echo.private('chat-message')
                .listen('.getChatMessage', (data) => {
                    if (sender_id != data.chat.sender_id)  {
                        var messageData = '<li class="other">\n' +
                            '                 <div class="msg">\n' +
                            '                      <p>'+ data.chat.message+'</p>\n' +
                            '                      <time>'+ data.chat.created_at+'</time>\n' +
                            '                  </div>';
                            '               </li>';
                        $('.chat').append(messageData)
                    }
                })
            })
  • Run the below command in your project for a one-to-one chat.
    • php artisan serve
    • npm run dev
    • php artisan queue:listen
    • php artisan reverb:start

You may also like

Leave a Reply