Laravel broadcasting with redis and socket.io

  • 04-05-2022
  • 1462
  • Laravel 9
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Hello Artisan,

In this post, we'll learn how to deploy a real-time chat system in laravel using the Redis server with the socket.io

Here we use the Redis server for broadcast real-time data and also use the laravel echo server for event listening

Redis server is lightweight for real-time chat systems.

You can easily install the Redis server and make sure to configure it as per your requirements.

In this tutorial, you can easily do it you have just followed a few steps one by one to create event sending using real-time broadcasting in laravel.

Sometimes it's making some difficulty for a developer with connecting with the server, or other things like broadcasting issues, Redis server issues, or many more things, here surely example please follow each step and integrate in your application easiest way, here below the working example code, so please follow it.

Step 1 : Install Laravel

Here, needs to clone the fresh laravel application.

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

Step 2 : Install predis

In this step we need to install predis as following command.

composer require predis/predis

Step 3 : Make Event

Here, need to create the event for broadcasting data. So follow the below command.

php artisan make:event ChatMessage

app/Events/ChatMessage.php

<?php
namespace App\Events;

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

class ChatMessage implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $userData = ['john'];

    /**
     * Create a new event instance.
     *
     * @return void
     */

    public function __construct()
    {
    	
    }
    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */

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

    /**
     * The event's broadcast with.
     *
     * @return string
     */
    public function broadcastWith()
    {
        return ['message'=>"Hello world, I'm John Smith"];
    }
}

Step 4 : Update .env file

In this step you need to changes in .env file.

Please follow the below example for set data in .env

.env

BROADCAST_DRIVER=redis

DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

REDIS_HOST=localhost
REDIS_PASSWORD=null
REDIS_PORT=6379

LARAVEL_ECHO_PORT=6001

Step 5 : Update config/database.php file

Now you need changes in config/database.php so let's do it.

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),
    ],
],

Now we need to add migration to our app.

So, Open your terminal and fire the below command.

php artisan migrate

Step 6 : Install Laravel Echo Server

Here we need to configure laravel-echo-server so let's do it.

Install laravel-echo-server

npm install -g laravel-echo-server

Init laravel-echo-server

laravel-echo-server init

After running the above command, please configure the like this

? Do you want to run this server in development mode? Yes
? Which port would you like to serve from? 6001
? Which database would you like to use to store presence channel members? redis
? Enter the host of your Laravel authentication server. http://localhost:8000
? Will you be serving on http or https? http
? Do you want to generate a client ID/Key for HTTP API? No
? Do you want to setup cross domain access to the API? No
? What do you want this config to be saved as? laravel-echo-server.json
Configuration file saved. Run laravel-echo-server start to run server.

After done above configuration, You get laravel-echo-server.json on project.

laravel-echo-server.json

{
	"authHost": "http://localhost:8000",
	"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 7 : Install npm, socket.io-client, laravel-echo

Now, Install npm, socket.io-client or laravel-echo

So let's fire one by one commands on terminal

npm install

npm install socket.io-client

npm install laravel-echo

Now we need to create the file laravel-echo-setup.js file on resources/js/ directory.

resources/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
});

Now we need to add on webpack.mix.js file as like bellow:

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

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

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css');
mix.js('resources/js/laravel-echo-setup.js', 'public/js'); /* like this */

After put above code, then you need to run npm run dev command.

npm run dev

Step 8 : Now Update View File

Here we need to update welcome.blade.php file on our project so let's updated it.

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 Redis Socket io</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">
            <div id="appendData"></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">

        window.Echo.channel('chat')
         .listen('ChatMessage', (response) => {
            $("#appendData").append('<div class="alert alert-success">'+response.message+'</div>');
        });

    </script>

</html>

Step 9 : Fire Event

In this step we need to call event using routes, So let's do it.

routes/web.php

Route::get('/fired', function () {
	event(new \App\Events\ChatMessage());
	dd('Event fired.');
});

Now we can run this example, Before you run this example make sure you have a Redis server installed on your system or server.

If you do not have a Redis server in your system or server then fire the below command and install it.

sudo apt install redis-server

After installing the Redis server you need to start larvel-echo-server So let's do it.

laravel-echo-server start

Now we run our laravel app following the command

php artisan serve

Now open your browser and run the below URL

http://localhost:8000/

After running the laravel project we need to test event broadcasting.

So let's fire event.

http://localhost:8000/fired

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 :