How to install Reverb in Laravel 11

by Tarun Korat Apr 04, 2024 Total Views: 136

Laravel Reverb brings blazing-fast and scalable real-time WebSocket communication directly to your Laravel application, and provides seamless integration with Laravel’s existing suite of event broadcasting tools.


Prerequisites


You'll need the following tools for the app that we'll build in this article:

Please ensure that your system meets the following requirements:


  • - PHP: Version 8.2 or above (run `php -v` to check the version)
  • - Composer: Verify its existence by running `composer` in your terminal.
  • - Node.js: Version 20 or above (run `node -v` to check the version)
  • - MySQL: Version 5.7 or above (run `mysql --version` to check if it exists, or refer to the documentation for installation instructions)


Installation


You may install Reverb using the install:broadcasting Artisan command:

php artisan install:broadcasting


Configuration


In the background, executing the install:broadcasting Artisan command triggers the reverb:install command, setting up Reverb with practical default configuration options. Should you wish to customize any settings, simply adjust Reverb's environment variables or modify the config/reverb.php configuration file.


Application Credentials


To connect to Reverb, both the client and server need to exchange a set of Reverb "application" credentials. These credentials, configured on the server, are essential for verifying requests from the client. You can define these credentials using the following environment variables:


REVERB_APP_ID=my-app-id
REVERB_APP_KEY=my-app-key
REVERB_APP_SECRET=my-app-secret


Create the Model and Migration


php artisan make:model -m Message


<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;


class Message extends Model
{
    use HasFactory;


    protected $table = 'messages';
    protected $fillable = ['user_id', 'text'];


    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }


    public function getTimeAttribute(): string
    {
        return Carbon::parse($this->created_at)->format("d M Y, H:i:s");
    }
}



Here's how you can set up the migration for the messages database table:

<?php


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


class CreateMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->text('text')->nullable();
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('messages');
    }
}



We will utilize MySQL as the primary database, but you have the option to use SQLite as the default database if you prefer. Ensure to accurately set up your database credentials in the .env file.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=username
DB_PASSWORD=password


Now run the migration for fresh and create your database.

php artisan migrate:fresh


Now Setting up Controller, Route, Blade, and Channel


1.Controller Creation

<?php

namespace App\Http\Controllers;

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

class ChatController extends Controller
{
    public function store(Request $request)
    {
        $message = $request->input('message');

        MessageSent::dispatch($message);
        return response()->json(['success' => true, 'message' => 'Message sent successfully']);
    }
}


Next, define the routes for displaying the chat view and handling the message sending action. Open the `web.php` file located in the `routes` directory and include the following:


use App\Http\Controllers\ChatController;

Route::get('/', function () {
    return view('chat');
});

Route::post('/chat/send-message', [ChatController::class, 'store'])->name('chat.send');


2.Blade View Creation

Generate a new Blade file called chat.blade.php within the resources/views directory. This file will encompass the HTML structure of your chat application. Insert the following code into it:


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chatroom</title>
    <!-- Include CSS and JS using Vite -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
<div id="app" class="p-6">
    <div id="chatroom" class="max-w-md mx-auto bg-white shadow-lg rounded-lg overflow-hidden">
        <div class="p-4 bg-gray-200">
            <div class="text-lg font-semibold">Chatroom</div>
        </div>
        <div class="p-4">
            <div id="messages" class="h-64 overflow-y-scroll">
                <div class="bg-gray-100 text-gray-800 p-3 rounded-lg m-2 self-start">
                    <p>This is a message from another user.</p>
                    <div class="text-right text-sm text-gray-500">User Name, 10:00 AM</div>
                </div>
            </div>
            <div class="mt-4">
                <input type="text" id="messageInput" class="w-full p-2 border rounded" placeholder="Type your message here...">
                <button onclick="sendMessage()" class="mt-2 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700 transition ease-in-out duration-150">Send Message</button>
            </div>
        </div>
    </div>
</div>
<!-- Include the necessary JavaScript for sending messages -->
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>


4. Setting Up the Channel


Broadcast::channel('chatroom', function () { return true; });


5.Creating the Event for MessageSent


First, create a new PHP file in the App\Events directory and name it MessageSent.php. Open the newly created file and add the following code:


<?php


namespace App\Events;


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


class MessageSent implements ShouldBroadcastNow
{
    use Dispatchable, SerializesModels;


    public $message;


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


    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('chatroom');
    }


    /**
     * Get the data to broadcast.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return [
            'message' => $this->message
        ];
    }


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



Here’s the code for chat-scripts.js:

// Listen for new messages using Laravel Echo
window.Echo.channel('chatroom')
  .listen('.message.sent', (e) => {
    console.log(e);
    // Append the new message to the chatroom
    const messages = document.getElementById('messages');
    const messageElement = document.createElement('div');
    messageElement.className = 'bg-gray-100 text-gray-800 p-3 rounded-lg m-2 self-end';
    const messageText = document.createElement('p');
    messageText.innerText = e.message;
    const messageTime = document.createElement('div');
    messageTime.className = 'text-right text-sm text-gray-500';
    messageTime.innerText = new Date().toLocaleTimeString();
    messageElement.appendChild(messageText);
    messageElement.appendChild(messageTime);
    messages.appendChild(messageElement);
  });

// Function to send a new message
window.sendMessage = function() {
  const messageInput = document.getElementById('messageInput');
  const message = messageInput.value;
  axios.post('/chat/send-message', { message: message })
    .then(response => {
      console.log(response.data);
      // Clear the input field after sending
      messageInput.value = '';
    })
    .catch(error => console.error(error));

  console.log('sent message');
};


In app.js, simply add the following import statement:


import './bootstrap'; import './chat-scripts';


Starting Laravel’s Real-Time Event Broadcasting Server


php artisan reverb:start


Starting Laravel’s Server

php artisan serve

Starting Vite Server

npm run dev


Congratulations! You've successfully set up a real-time chat application running locally. This setup enables immediate feedback and iteration, which is invaluable during development.


Tags: Laravel Reverb Laravel 11 installation guide audio management Laravel audio package

Please login to create comment.

Author
Author Image

"Tarun Korat, an avid wordsmith and passionate storyteller, pours his creativity into every piece he writes. With a knack for weaving engaging narratives, Tarun captivates readers with his insightful perspectives on life, love, and everything in between. Join him on his literary journey as he shares his thoughts and musings through the power of words."

- Tarun Korat
Follow Me: