Friday, February 28, 2020

Laravel 6 Event Broadcasting Socket.io Tutorials


Laravel 6 Event Broadcasting Socket.io Tutorials

Hello Buddies

In this tutorial I will guide you step by step through the use of event transfer with redis, socket.io and laravel-echo-server in the laravel 6 application. I will give you an example of a real-time broadcast message with io-socket in laravel 6. In laravel 6, Predis, Queue, Socket.io, Laravel-Echo-Server and event transmission are used.

You can easily do this. Just follow a few steps to create event sending using real-time broadcasting in Laravel 6.

Laravel has an event transfer problem. The transmission of events is very interesting and particularly difficult to implement with redis and socket.io. However, I will give you step-by-step instructions for sending real-time messages with quiet and socket io in the Laravel 6 application.

You only need to take a few steps to do the following. So follow the next steps and make real-time notification with Laravel.

Step 1: install Laravel 6


First, we need to get a new version of Laravel 6 with the following command because we are working from scratch. So open your terminal OR prompt and run the following command:

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


Step 2: install Predis


In this step we have to install predis as follows. So run the following command to install predis in the Laravel application.

composer require predis/predis


Step 3: create event


Here we have to create an event for the broadcast. In the event file, we need to set up the channel and send the message array with the key. Then run the following command to create an event.

php artisan make:event SendMessage

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'=>'This notification from ItSolutionStuff.com'];

    }

}


Step 4: Update the configuration file


In this step we need to add the configuration set in the env file and the database configuration file. You must configure the env file with BROADCAST_DRIVER as a redis and database configuration as well as a database redis configuration.

We will update the files:

.env
BROADCAST_DRIVER=redis

  

DB_DATABASE=blog_chat

DB_USERNAME=root

DB_PASSWORD=root

  

REDIS_HOST=localhost

REDIS_PASSWORD=null

REDIS_PORT=6379

   

LARAVEL_ECHO_PORT=6001


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 have to do the migration too.

So let's do the migration.

php artisan migrate


Step 5: Install the Laravel Echo Server


In this step we need to install the Laravel Echo Server on your system and in your project. So run the following command to install laravel-echo-server and init.

Install laravel-echo-server

npm install -g laravel-echo-server

Init laravel-echo-server

laravel-echo-server init

A new laravel-echo-server.json file is created as follows:

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


Here we install npm and also laravel-echo, socket.io-client. You also need a configuration. Then run the following command:

npm install

npm install laravel-echo

npm install socket.io-client

Now we have to create a new laravel-echo-setup.js file in the asset 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

});


You should now add the mix file as follows:

webpack.mix.js
...

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

Now we need to run the npm run command:

npm run dev


Step 7: update the view file


Now we have to update our Welcome Blade file. Here's how you can see our code:

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 Tutorial - ItSolutionStuff.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">

            <h1>Laravel Broadcast Redis Socket io Tutorial - ItSolutionStuff.com</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: call event


Here we create a new test route for the calling event. Then let's add the following route as shown below:

routes/web.php
Route::get('/t', function () {

    event(new \App\Events\SendMessage());

    dd('Event Run Successfully.');

});


Now we can run our example. However, follow the instructions below to complete your project.

You must install the Redis server on your system or server. Then you cannot install it with the following command:

sudo apt install redis-server

You can then start the Laravel echo server as follows:

laravel-echo-server start

You can now run the project using the following command:

php artisan serve

You can now open the following URL in your browser:

http://localhost:8000/

Now you can photograph your event with this URL:

http://localhost:8000/t


I hope I can help you ...

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.