Laravel Advance | Laravel Broadcast Redis Socket io Tutorial
Today, our leading topic is event broadcasting with Redis and socket.io in the laravel application. I want to give you a very simple example of a laravel broadcast using rest and socket io in the laravel application. you can send real-time chat messages using rest socket io and event broadcasting with laravel 6, laravel 7, and laravel 8 applications.
Laravel provides event broadcasting topics. event broadcast is very interesting and it’s also difficult to implement with Redis and socket.io especially. but I will give you step-by-step instructions on how to send real time messages with rest and socket io in laravel 6 application.
You need to just follow a few steps to do the following thing. so let’s follow the below steps and do a real-time notification with laravel.
Step 1: Install Laravel
First of all, we need to get a 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 below command. so let’s run the following command to install prides in the laravel app.
composer require predis/predis
Step 3: Create Event
Here, we need to create an event for broadcasting. in the event file, we need to set the channel and send the message array with a key. so, let’s run the following command for creating an event.
php artisan make:event SendMessage
app/Events/SendMessage.php+
<?phpnamespace 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'];}}
Step 4: Update Configuration File
In this step, we need to add a set configuration on the env file and database configuration file. 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=redisDB_DATABASE=blog_chatDB_USERNAME=rootDB_PASSWORD=rootREDIS_HOST=localhostREDIS_PASSWORD=nullREDIS_PORT=6379LARAVEL_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 the migration.
php artisan migrate
Step 5: Install Laravel Echo Server
In this step, we need to install a laravel-echo-server in your system and in your project. so let’s 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
You have to set up your configuration. you can see the below screenshot:
It will create a 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 configure. so let’s run the following command:
npm installnpm install laravel-echonpm install socket.io-client
Now we need to create a new file laravel-echo-setup.js file on the 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 the 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</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</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 will create a new testing route for the call events. so, let’s add the following route as bellow:
Step 8: Call Event
Here, we will create a new testing route for call events. so, let’s add the following route as bellow:
routes/web.php
Route::get('/t', function () {event(new \App\Events\SendMessage());dd('Event Run Successfully.');});
Now we are ready to run our example but make sure to follow things to run your project.
You must have to install the Redis server in your system or server. it not then you can install using the following command
sudo apt install redis-server
After that you can start the laravel echo server as like bellow command:
laravel-echo-server start
Now you can run the project using the following command:
php artisan serve
Now you can open bellow URL on your browser:
http://localhost:8000/
Now you can fire your event by this URL:
http://localhost:8000/t
I hope it can help you…