Real-Time Laravel Broadcasting integration

Real-Time Laravel Broadcasting Integration In 5 Easy Steps

August 25, 2020Posted By: ZealousWeb
Framework TutorialsLaravel BroadcastingRealtime Integration

Introduction

When you think of Laravel broadcasting for real-time applications in Laravel, pairing the Redis broadcaster with a Socket.IO server is an effective strategy. Numerous Laravel development companies, including those specializing in Laravel broadcast solutions, might have different methodologies. However, these five steps, embraced by seasoned Laravel developers, made our Laravel web development project a breeze. Leveraging Laravel websocket technology further enhances real-time capabilities, showcasing why we’re a leading Laravel development company in this field.

Follow These 5 Easy Steps For Broadcasting Integration

  1. Configure Redis
  2. Create Event And Fire Event
  3. Install Required Packages
  4. Configure Socket.IO
  5. Setup Websocket And Consume Data

Step 1: Configure Redis

To configure Redis into Laravel – you will need to install the package using the below command:

composer requires predis/predis

After a successful installation, configure the Redis host, client, and database details in the config/database.php file as follows:

'redis' => [ 'client' => 'predis', 'default' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => env('REDIS_DATABASE', 0), ], ],

OR you can configure that from .env file also like below:

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
REDIS_DATABASE=0

To update the broadcast method as Redis in config/boradcasting.php,

'default' => env('BROADCAST_DRIVER', 'redis'),

OR you should update your broadcast driver to Redis in your .env file:

BROADCAST_DRIVER=redis

You will need to register the App\Providers\BroadcastServiceProvider for broadcasting events.

Also, do not forget to uncomment or add Illuminate\Broadcasting\BroadcastServiceProvider: class provider in the providers’ array of your config/app.php configuration file to allow you to register the broadcast authorization routes and callbacks.

Step 2: Create Event And Fire Event

We will need to create an event for broadcasting data. Run the below command to create an event file.

php artisan make: event ActionEvent

It will create a file that looks like the one below:

<?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\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class ActionEvent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; /** * 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 PrivateChannel('channel-name'); } }

BroadcastOn method is responsible for returning the channels that the event should broadcast on. It should be instances of Channel, PrivateChannel, or PresenceChannel. Also, you can control your broadcast payload by using the broadcastWith method for your event.

<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; class ActionEvent implements ShouldBroadcastNow { use Dispatchable, InteractsWithSockets, SerializesModels; public $actionId; public $actionData; /** * Create a new event instance. * * @author Author * * @param mixed $actionId * @param mixed $actionData * @return void */ public function __construct($actionId, $actionData) { $this->actionId = $actionId; $this->actionData = $actionData; } /** * Get the channels the event should broadcast on. * * @author Author * * @return Channel|array */ public function broadcastOn() { return new Channel('action-channel-one'); } /** * Get the data to broadcast. * * @author Author * * @return array */ public function broadcastWith() { return [ 'actionId' => $this->actionId, 'actionData' => $this->actionData, ]; } }

Also, you can customize the broadcast name by defining a “broadcastAs” method on the event. If you modify your broadcast name using the “broadcastAs” method, you must register your listener with a leading character. You can customize the queue by defining a “broadcastQueue” property in your event class. You can also add conditions for broadcast data by adding a “broadcastWhen.”

After that, we will fire the event to broadcast data.

event(new ActionEvent($actionId, $actionData));

Let’s take one example: we fired an event with a team score for a gaming app.

$actionId = 'score_update'; $actionData = array('team1_score' => 46); event(new ActionEvent($actionId, $actionData));

Step 3: Install Required Packages

You must install “Node.js” and “redis-server” in your system or server. To install “redis-server,” you can use the below command:

npm install Redis-server

You can verify whether Redis is running correctly or not using the command “redis-cli ping.” It will return “pong” if Redis is installed and running.

You must install packages express, ioredis, socket.io, and dotenv. So run the below command:

npm install express ioredis socket.io dotenv –save

Step 4: Configure Socket.IO

Now, set up a socket server to listen and capture Redis channel messages to broadcast, which are fired from events. Create a “server.js” file in the project root directory and add the below code.

'use strict'; var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); require('dotenv').config(); var redisPort = process.env.REDIS_PORT; var redisHost = process.env.REDIS_HOST; var ioRedis = require('ioredis'); var redis = new ioRedis(redisPort, redisHost); redis.subscribe('action-channel-one'); redis.on('message', function (channel, message) { message = JSON.parse(message); io.emit(channel + ':' + message.event, message.data); }); var broadcastPort = process.env.BROADCAST_PORT; server.listen(broadcastPort, function () { console.log('Socket server is running.'); });
  • We have created the Redis object by connecting it to the Redis server and port.
  • We need to subscribe to the channels on which data will be broadcast. We can subscribe to multiple channels.
  • When we fire an event, it will push data into Redis—using Redis. on(‘message’), the event system will get a message and channel name. Then, using io. emit, it will broadcast data on a broadcastPort. Server. listen will listen to incoming requests from broadcastPort.
  • You can run the script by calling the command “node server.js.” It will print the “Socket server is running.” into the console.

Step 5: Setup Websocket And Consume Data

After successfully setting up broadcast data, we will set up a websocket channel and connect the publish URL on the page where we need to show real-time changes.

You will need to configure the publisher URL into your .env.

PUBLISHER_URL=http://127.0.0.1

Into your page, add a code like the one below to get a message from the broadcast channel.

<div class="container"> <h1>Team A Score</h1> <div id="team1_score"></div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> <script> var sock = io("{{ env('PUBLISHER_URL') }}:{{ env('BROADCAST_PORT') }}"); sock.on('action-channel-one:App\\Events\\ActionEvent', function (data) { // data.actionId and data.actionData hold the data that was broadcast // process the data, add needed functionality here var action = data.actionId; var actionData = data.actionData; if (action == "score_update" && actionData.team1_score) { $("#team1_score").html(actionData.team1_score); } }); </script>

The sock. on() will listen to a specific channel on the Websocket. We must pass the socket channel name the same way we give it to the “server.js” script, e.g., channel-name: EventName. We can create multiple socks.on() calls to listen to different Websocket channels.

Conclusion

I hope it will help you make real-time applications like chatbots and games with live score updates and broadcast some notice to all users. Regarding Laravel broadcasting, there are other methods for receiving broadcasts. You can also use the JavaScript library Laravel Echo to subscribe to channels and receive messages from the broadcast.

At ZealousWeb, our recent project includes the implementation of this robust functionality. We used real-time Laravel broadcasting to build a game that involves participants and judges from across the world. It is a scheduled game that needs active participation from pre-listed candidates and works in real time. If you’re seeking experienced Laravel developers to implement Laravel broadcasting in your projects, our Laravel development company has the needed expertise. For more information or to get in touch with our team, feel free to contact us. We’re here to help bring your projects to life with our specialized skills and innovative solutions.

Does that sound exciting to you? It sure was for us to create the game!

You can always get in touch to learn more about how we created certain functionalities or ask us, a Laravel development company, to create it for you! Alternatively, you can hire a Laravel developer from us who’ll work only on your project.

FAQ

What Could Be The Causing Issue With Subscribe And Broadcast In Redis + Socket.IO?

Why Is Broadcast On A Private Channel Not Working?

How To Authenticate A Private Channel Using Redis And Socket.IO?

Subscribe To Our Newsletter

Related Blog Posts

ExpressionEngine Add-Ons

14 ExpressionEngine Add-Ons To Take Your Site To The Next Level

Content ManagementWeb Development ToolsWebsite Enhancement
tips to hire a Magento developer

Unlocking The Secrets To Hiring An Outstanding Magento Developer

Developer SecretseCommerce HiringMagento Development
The power of WooCommerce

How WooCommerce Development Services Can Change The Game Of e-Commerce?

Development ServiceseCommerce SolutionsWooCommerce Services
OptimizingeCommerce Website

10 Things To Keep In Mind For Your Online e-Commerce Store

eCommerce TipsStore OptimizationSuccess Strategies
WordPress maintenance service

6 Useful Tips To Consider For WordPress Maintenance

Website ManagementWebsite SecurityWordPress Maintenance
ExpressionEngine Plugin

A Complete Guide On Creating An ExpressionEngine Plugin

Plugin DevelopmentWeb Development TutorialWebsite Plugin Creation