Laravel Echo, Socket.io and Redis Setup

Laravel introduced the Broadcasting event if your working on web applications that require real-time responses through WebSocket. You can send messages to a server and receive event-driven responses.

Table of content

Setup Laravel Echo Server

Laravel Echo Server is a Nodejs server for Laravel Echo broadcasting. You can install it globally or for a particular project. We are installing it globally to our system.

npm install -g laravel-echo-server

Now go to your project directory and generate the laravel echo server configuration file.

laravel-echo-server init

The above command will generate the laravel-echo-server.json file. Something similar to below file.

{
	"authHost": "http://localhost:8000",
	"authEndpoint": "/broadcasting/auth",
	"clients": [],
	"database": "redis",
	"databaseConfig": {
		"redis": {
			"host": "172.20.10.13"
		},
		"sqlite": {
			"databasePath": "/database/laravel-echo-server.sqlite"
		}
	},
	"devMode": true,
	"host": "localhost",
	"port": "6001",
	"protocol": "http",
	"socketio": {},
	"secureOptions": 67108864,
	"sslCertPath": "",
	"sslKeyPath": "",
	"sslCertChainPath": "",
	"sslPassphrase": "",
	"subscribers": {
		"http": true,
		"redis": true
	}
}

In my case, I have installed the Redis on Virtual Machine and I have used my virtual machine IP on Redis configuration.

"redis": {
        "host": "172.20.10.13"
}

Setup Redis

Make sure you have installed the Redis on your machine. Or you can follow the below steps to install the Redis on your local machine.

wget http://download.redis.io/releases/redis-5.0.5.tar.gz
tar xzf redis-5.0.5.tar.gz
cd redis-5.0.5
make

Or you can simply follow the installation instructions from the Redis documentation.

Setup Laravel Echo & Socket.io

Now it’s time to setup client-side dependencies. To communicate with Laravel Echo Server, we required to install Laravel Echo and Socket.io.

npm install --save laravel-echo socket.io-client

Once the installation completes, open the bootstrap.js file. This file is located at resources/js directory. We have to implement the Laravel Echo and Socket.io to the bootstrap.js file to communicate with the Echo Server. Add the following codes at the end of the bootstrap.js file.

import Echo from 'laravel-echo'

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001'
});

Now time to start laravel-echo-server to check the connection. Use the laravel-echo-server start command to start the echo server.

Hope all the above steps will help you to set up the laravel echo server, socket.io and redis correctly.