Laravel Event Broadcast With Redis Socket.io Echo To Listen Real-Time Message

  • 09-07-2022
  • 2352
  • Laravel 9
  • Haresh Chauhan

What Is Laravel Broadcasting?

Laravel broadcasting allows you to broadcast your event from the server-side to the client-side javascript application using the driver-based approach to WebSockets. Now laravel shipped with pusher channel still there are many marketer providers available paid or free.

What Is Websocket?

Laravel WebSocket is a package for the laravel composer that will allow you to send get client-side messages retrieved from the socket server in real-time. It will send you a real-time message from the laravel broadcasting.

About Post :

In this post, we will learn how to do laravel broadcasting using the Redis server and how to listen to this broadcasting event using the echo server. If you are interested in real-time chat and message integration in your laravel application then this post help you to integrate.

First, Take a preview of how the event sends to the Redis server and then how this listens to the server using the echo server.

Here we have taken the Redis server for the real-time cache store in the server.

OUTPUT PREVIEW :

image

So let's start integration, follow each step, and integrate into your project. This is very simple and easy to integrate.

Step 1: Create Laravel Project

First, We will create a fresh laravel project using the below given suggested command. So copy this command and paste it into your terminal.

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

cd broadcasting

Step 2: Composer Install Predis

We will install a composer for the predis server. Go to your terminal and run this command this will install predis composer in your project.

composer require predis/predis

Step 3: Database Configuration

Config your database, we will set broadcasting driver Redis because we will use the Redis server for the broadcasting. After it we will config normal database configuration, also we will config Redis server configuration.

.env

BROADCAST_DRIVER=redis

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=broadcasting
DB_USERNAME=root
DB_PASSWORD=

REDIS_HOST=localhost
REDIS_PASSWORD=null
REDIS_PORT=6379

LARAVEL_ECHO_PORT=6001

It might happen that your .env file not working, we will clear the cache so this will not raise the issue in the ahead step.

php artisan config:cache

php artisan config:clear

Step 4: Redis Configuration

We will config Redis server, In client attribute we will replace from phpredis to predis and also we will remove prefix from the options.

config/database.php

'redis' => [

    'client' => env('REDIS_CLIENT', 'predis'),

    'options' => [
        'cluster' => env('REDIS_CLUSTER', 'redis'),
        'prefix' => env('REDIS_PREFIX',''),
    ],

    'default' => [
        'url' => env('REDIS_URL'),
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', '6379'),
        'database' => env('REDIS_DB', '0'),
    ],

    'cache' => [
        'url' => env('REDIS_URL'),
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'password' => env('REDIS_PASSWORD', null),
        'port' => env('REDIS_PORT', '6379'),
        'database' => env('REDIS_CACHE_DB', '1'),
    ],

],

Step 5: Event Create

Now, We will create a event using below command, This command will create a event SendMessage in your events folder inside the app folder of your laravel application.

php artisan make:event SendMessage

Step 6: Config Event

In this step, we will config the event class which we created earlier. In the construct method we are passing a message.

broadcastOn we will define the channel name send-chat-message.

broadcastAs in this method, we will define the channel listen to name SendChatMessage.

broadcastWith we will pass the data on the broadcasting.

<?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\Queue\SerializesModels;

class SendMessage implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $data;

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

    /**
    * Get the channels the event should broadcast on.
    *
    * @return \Illuminate\Broadcasting\Channel|array
    */
    public function broadcastOn()
    {
        return new Channel('send-chat-message');
    }

    /**
    * The event's broadcast name.
    *
    * @return string
    */
    public function broadcastAs()
    {
        return 'SendChatMessage';
    }

    /**
    * The event's broadcast name.
    *
    * @return string
    */
    public function broadcastWith()
    {
        return ['title'=> $this->data ];
    }
}

Step 7: Migrate Database

Migrate database using the given command.

php artisan migrate

Step 8: Install Laravel Echo Server

Use this given below command in your laravel project directory terminal, This will create a laravel echo server for event broadcasting.

npm install -g laravel-echo-server

Step 9: Init Echo Server

Copy this command and paste it into your terminal. It will ask for some configuration setup as below given in the image.

laravel-echo-server init

Config you echo server as given in image, So you are using in local server else setup according to ask.

image

Once you init your echo server. On the root will create a file laravel-echo-server.json. This will something look like below given example.

laravel-echo-server.json

{
    "authHost": "http://localhost",
    "authEndpoint": "/broadcasting/auth",
    "clients": [],
    "database": "redis",
    "databaseConfig": {
        "redis": {},
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": null,
    "port": "6001",
    "protocol": "http",
    "socketio": {},
    "secureOptions": 67108864,
    "sslCertPath": "",
    "sslKeyPath": "",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "subscribers": {
        "http": true,
        "redis": true
    },
    "apiOriginAllow": {
        "allowCors": false,
        "allowOrigin": "",
        "allowMethods": "",
        "allowHeaders": ""
    }
}

Step 10: Npm Install

Next, We will install the node package in our project using the below command.

npm install

After installing node modules in the project. We will install the npm laravel echo server in our node package.

npm install laravel-echo

Install socket. io-client for the in your node module.

npm install socket.io-client

Step 11: Add Laravel Echo Setup File

Add this below-given code in your laravel-echo-setup.js go to your resources folder and create folder assets and then in this create js folder and in this folder create a file.

resources/assets/js/laravel-echo-setup.js

import Echo from 'laravel-echo';

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ":" + window.laravel_echo_port
});

Step 12: Mix Assets

Goto root and config your webpack.mix.js file.

webpack.mix.js

const mix = require('laravel-mix');

/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
|
*/

mix.js('resources/js/app.js', 'public/js')
    .js('resources/assets/js/laravel-echo-setup.js', 'public/js') // add
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);

Now we will run our node server using the command.

npm run dev

Step 13: Blade File Setup

Replace your code with this content in your welcome blade file.

resources/views/welcome.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Laravel Broadcast With Redis Socket.io - Webappfix.com</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <h2>Laravel Broadcast With Redis Socket.io - Webappfix.com</h2>
            <div id="message"></div>
        </div>
    </body>
    
    <script>
            window.laravel_echo_port='{{env("LARAVEL_ECHO_PORT")}}';
    </script>
    <script src="//{{ Request::getHost() }}:{{env('LARAVEL_ECHO_PORT')}}/socket.io/socket.io.js"></script>
    <script src="{{ url('/js/laravel-echo-setup.js') }}" type="text/javascript"></script>
        
    <script type="text/javascript">
        var i = 0;
        window.Echo.channel('send-chat-message')
            .listen('.SendChatMessage', (data) => {
            i++;
            $("#message").append('<div class="alert alert-success">'+i+'.'+data.title+'</div>');
        });
    </script>
</html>

Step 14: Route For Run Event

Call event in your route file and pass a param in your event for dynamic data to send.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::get('test-event/{body}',function($body){

    try {
        event(new \App\Events\SendMessage($body));

        dd('Message Successfully Sended.');

    } catch (\Throwable $th) {

        throw $th;
    }
});

Step 15: Redis Server Install

If you still have not installed the Redis server in your system, Install it else skip it.

sudo apt install redis-server

After the Redis server is installed, Goto your Redis serve path in your terminal and start your Redis server.

redis-server

The above-given command will start your Redis server.

image

Goto root in the terminal and run start your echo server.

laravel-echo-server start

Once you enter the command it will something look like this. Keep running don't close the terminal.

Start the laravel development server.

php artisan serve

Run Even listening route.

http://localhost:8000/

Send a message using the given URL.

http://127.0.0.1:8000/test-event/Test-Message

Once you send an event message you can see in your echo server start terminal that there is also the happening message which you send from the event.

image

Conclusion

Laravel broadcasting we used Redis server but still, there are many marketers provider available for it to fetch real-time messaging from the server to the client-side without any extra configuration. like pusher and one-signal. Redis is a power full serve to exchange chase between server-side to client-side and it's free. also paid Redis server is available you extra tool you can use it too. I hope this post helped you to integrate laravel event broadcasting using Redis server.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :