Realtime Event Broadcasting using Socket.io in Laravel7.x with Example

  671 views   3 months ago Laravel

In the today’s technogy age genuine time data has become an essential thing. So here, in this article i will apportion laravel authentic time event broadcasting with socket.io. Here in this example we will visually perceive how can we broadcast genuine times events.

Fundamentally, to acheive this thing in our laravel application, we will utilize predis which is a laravel package, queue, socket.io, laravel-echo-server and event broadcasting.

So, we will require to install the above things which are not provided in the laravel appication by default. I will provide all the step to implement genuine time broadcasting event in the sundry steps from a fresh installation of laravel application. If you have already installed laravel application then you can directly jump on the next step. So without wasting our time let’s start the implementation process and follow all the steps as given below.

Step 1: Install Laravel

For installing fresh laravel application, you will just needto run the following command in your terminal or command prompt.

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

I have given a name realtimeapp to this application, you are frre to give the name of your choice.

Now, run the following command to give permission to the storage and cache directories.

sudo chmod -R 777 /var/www/html/realtimeapp/storage
sudo chmod -R 777 /var/www/html/realtimeapp/bootstrap/cache<br><br>

Step 2: Install predis

In this second step, we will need to install predis. So open your terminal and run the following command.

composer require predis/predis

Step 3: Create event for broadcasting

Now we will need to create an event for broadcasting and in the event file we will set channal and write message. So run the following command to create event.

php artisan make:event SendMessage

Above command will create an event file SendMessage.php file under app/Events directory. So open this file and update it like below.

app/Events/SendMessage.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;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
  
class SendMessage implements ShouldBroadcastNow
{
    use InteractsWithSockets, SerializesModels;
  
    public $data = ['asas'];
  
    /**
     * 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('user-channel');
    }
  
    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'UserEvent';
    }
    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastWith()
    {
        return ['title'=>'Notification message will go here'];
    }
}

Step 4: Update Configuration Settings

Here we will update some configurations like Broadcast driver, database details etc. So open up .env file and add the configurations like mentaioned in the code below.

.env

BROADCAST_DRIVER=redis
  
DB_DATABASE=chat_app
DB_USERNAME=db_username
DB_PASSWORD=db_password
  
REDIS_HOST=localhost
REDIS_PASSWORD=null
REDIS_PORT=6379
   
LARAVEL_ECHO_PORT=6001

And now database.php file will look a like below.

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

After doing the above thiings, open your terminal and run the migration command like below.

php artisan migrate

Step 5: Install Laravel Echo Server

In this step, we will install laravel echo server in our laravel web application. So your your terminal and execute the following command.

npm install -g laravel-echo-server

After installing laravel echo server using npm, we will need to initiate it using the command written below.

laravel-echo-server init

After running the above init command, a json file (laravel-echo-server.json) would be created and this file will look a like below.

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 6: Install npm, laravel-echo, socket.io-client

In this sixth step, we will run the laravel echo server, install laravel echo  and socket.io- client. So open your terminal and the commands as given below.

npm install

npm install laravel-echo

npm install socket.io-client

After running the above commands, we will create laravel-echo-setup.js file and will write a script to start laravel echo server. So create this file under resources/assets/js directory. And update the code as given below.

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

After doing the above things, we will need need to add the above laravel-echo-setup.js file to the mix file.

webpack.mix.js

...
mix.js('resources/assets/js/laravel-echo-setup.js', 'public/js');

Now, we will need to execute npm run using the command below.

npm run dev

Step 7: Create View File or blade template

Now, in this step we will create view file basically which is a blade file. So let’s create a file. Here i am giving a name notification.blade.php to this file and put the following code into this file.

resources/views/notification.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 real time event broadcasting with socket.io example</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">
            <h1>Laravel real time event broadcasting with socket.io example - LaravelCode</h1>
            
            <div id="notification"></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('user-channel')
         .listen('.UserEvent', (data) => {
            i++;
            $("#notification").append('<div class="alert alert-success">'+i+'.'+data.title+'</div>');
        });
    </script>
</html>

Step 8: Add route to call event

Now, we will need to route to call the event. So open routes/web.php file and add the route and event call as mentioned below.

routes/web.php

Route::get('/run-event', function () {
    event(new \App\Events\SendMessage());
    dd('Event Run Successfully.');
});

After following all the above steps, you have completed laravel real time event broadcasting with socket.io. But before starting you will have to be confirmed that you have installed redis server on your machine.

If not installed, you can run the following command to install redis server.

sudo apt install redis-server

Then start  laravel echo server using the command below

laravel-echo-server start

And at last we will need to deploy the application. For deploying on the local machine you can run the command below.

php artisan serve

Now you can check the application and the events by opening the url as given below.

http://localhost:8000/run-event

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles