How to use Laravel with Socket.IO

“Why don’t you just use Pusher?”

“We want to have an unlimited number of connections”

We don’t want to worry about limitations.

Create Your Event

php artisan make:event MessagePushed

Install Redis

BROADCAST_DRIVER=redisQUEUE_DRIVER=redis(this is from the horizon setup actually, but we will need that for later)REDIS_HOST=127.0.0.1REDIS_PASSWORD=nullREDIS_PORT=6379

Install Laravel Echo Server

npm install -g laravel-echo-server
laravel-echo-server init
{"authHost": "http://local-website.app","authEndpoint": "/broadcasting/auth","clients": [{"appId": "my-app-id","key": "my-key-generated-with-init-command"}],"database": "redis","databaseConfig": {"redis": {},"sqlite": {"databasePath": "/database/laravel-echo-server.sqlite"},"port": "6379","host": "127.0.0.1"},"devMode": false,"host": null,"port": "6001","protocol": "http","socketio": {},"sslCertPath": "","sslKeyPath": "","sslCertChainPath": "","sslPassphrase": ""}
laravel-echo-server start
[program:laravel-echo]directory=/var/www/my-website-folderprocess_name=%(program_name)s_%(process_num)02dcommand=laravel-echo-server startautostart=trueautorestart=trueuser=your-linux-usernumprocs=1redirect_stderr=truestdout_logfile=/var/www/my-website-folder/storage/logs/echo.log
pwd
sudo supervisorctl stop all sudo supervisorctl rereadsudo supervisorctl reload
sudo supervisorctl status

Install Laravel Echo and Socket IO client

npm install --save laravel-echonpm install --save socket.io-client
import Echo from "laravel-echo"window.io = require('socket.io-client');// Have this in case you stop running your laravel echo serverif (typeof io !== 'undefined') {  window.Echo = new Echo({    broadcaster: 'socket.io',    host: window.location.hostname + ':6001',  });}
public function broadcastOn(){return new PresenceChannel('survey.' . $this->survey->id);}
Broadcast::channel('survey.{survey_id}', function ($user, $survey_id) {return ['id' => $user->id,'image' => $user->image(),'full_name' => $user->full_name];});
listenForBroadcast(survey_id) {Echo.join('survey.' + survey_id).here((users) => {this.users_viewing = users;this.$forceUpdate();}).joining((user) => {if (this.checkIfUserAlreadyViewingSurvey(user)) {this.users_viewing.push(user);this.$forceUpdate();}}).leaving((user) => {this.removeViewingUser(user);this.$forceUpdate();});},

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store