Real Time Event Broadcasting with Laravel 7/6 and Socket.io

Real Time Event Broadcasting with Laravel 7/6 and Socket.io

In this post we will give you information about Real Time Event Broadcasting with Laravel 7/6 and Socket.io. Hear we will give you detail about Real Time Event Broadcasting with Laravel 7/6 and Socket.ioAnd how to use it also give you demo for it if it is necessary.

Hi Artisan,

In this tutorial, i will guide you step by step how to use event broadcasting using redis, socket.io and laravel-echo-server in laravel 7/6 application. i will give you example of real time broadcast message with socket io in laravel 7/6. we will use predis, queue, socket.io, laravel-echo-server and event broadcasting in laravel 7/6.

You can easily do it, you have to just follow few step to creating event sending using real time broadcasting in laravel 7.

Laravel provide event broadcasting topic. event broadcast is a very interesting and it’s also difficult to implement with redis and socket.io as specially. but i will give you step by step instruction of how to send real time message with rest and socket io in laravel 6 application.

You need to just follow few step to done this following thing. so let’s follow bellow steps and done as real time notification with laravel.

Step 1: Install Laravel 6

First of all, we need to get fresh Laravel 6 version application using bellow command because we are going from scratch, So open your terminal OR command prompt and run bellow command:

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

Step 2: Install predis

In this step, we need to install predis as bellow command. so let’s run following command to install predis in laravel app.

composer require predis/predis

Also see:Laravel 6 CRUD Application Tutorial

Step 3: Create Event

Here, we need to create event for broadcasting. in event file we need to set channel and send message array with key. so, let’s run following command for creating event.

php artisan make:event SendMessage

app/Events/SendMessage.php

<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;

use IlluminateQueueSerializesModels;

use IlluminateBroadcastingPrivateChannel;

use IlluminateBroadcastingPresenceChannel;

use IlluminateFoundationEventsDispatchable;

use IlluminateBroadcastingInteractsWithSockets;

use IlluminateContractsBroadcastingShouldBroadcast;

use IlluminateContractsBroadcastingShouldBroadcastNow;

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 IlluminateBroadcastingChannel|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 configuration File

In this step, we need to add set configuration on env file and database configuration file. you you need to set env file with BROADCAST_DRIVER as redis and database configuration and also database redis configuration.

Let’s updated 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 need to run migration also.

So, let’s run migration.

php artisan migrate


Step 5: Install Laravel Echo Server

In this step, we need to install laravel-echo-server in your system and in your project. so let’s run 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

You have to setup your configuration. you can see bellow screenshot:

It will create new file laravel-echo-server.json file as like bellow:

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 will install npm and also install laravel-echo, socket.io-client. also you need to configuration. so let’s run following command:

npm install

npm install laravel-echo

npm install socket.io-client

Now we need to create new file laravel-echo-setup.js file on assets 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

});

Now you need to add on mix file as like bellow:

webpack.mix.js

...

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

Now we need to run npm run command:

npm run dev

Step 7: Update View File

Now we need to update our welcome blade file. so you can see our there code as like bellow:

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 >

<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 >'+i+'.'+data.title+'</div>');

});

</script>

</html>

Step 8: Call Event

Here, we will create new testing route for call event. so, let’s add add following route as bellow:

routes/web.php

Route::get('/t', function () {

event(new AppEventsSendMessage());

dd('Event Run Successfully.');

});

Now we are ready to run our example, but make sure following thing to run your project.

You must have to install redis server in your system or server. it not then you can install using following command:

sudo apt install redis-server

After that you can start laravel echo server as like bellow command:

laravel-echo-server start

Now you can run project using following command:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/

Now you can fire you event by this url:

Also see:Laravel 7/6 Auth Login with Username or Email Tutorial

http://localhost:8000/t

You can see result as like bellow screen shot:

You can download code from git: Download Code from Github

I hope it can help you…

Hope this code and post will helped you for implement Real Time Event Broadcasting with Laravel 7/6 and Socket.io. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

7  +  1  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US