How to use Laravel with Socket.IO

You can find about it here: https://github.com/tlaverdure/laravel-echo-serverNote: Check the requirements at the top!Run the following (as stated in the document)npm install -g laravel-echo-serverAnd then run the init in order to get your laravel-echo-server.json file generated in the app root (which we will need to configure).laravel-echo-server initOnce you have generated your laravel-echo-server.json file, it should look like this.{"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": ""}Note: If you want to push this to your public server, make sure to add laravel-echo-server.json to your .gitignore and generate this file on the server, otherwise you will need to change your authHost all the time.Run your Laravel Echo ServerYou have to run it in order to start websockets.laravel-echo-server start (inside your root — where your laravel-echo-server.json is placed)It should start successfully..(Now we will want to add this to supervisor on your server so it is started automatically and restarted in case it crashes)Inside your /etc/supervisor/conf.d/laravel-echo.conf (just create this file inside your conf.d folder) place the following:[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.logOnce you position in your laravel root, you can runpwdto get the path for your ‘directory’ above and ‘stdout_logfile’ prefix.Your user will be your linux user (vagrant or ubuntu or some other)Save the file and go out.   (if you used vim laravel-echo.conf then when inside, press I (like Istanbul) on your keyboard to edit a file with VIM and then type ESC following :wq!.To close the file and save it.Next we need to run the following commands:sudo supervisorctl stop all sudo supervisorctl rereadsudo supervisorctl reloadAfter that check to see if laravel echo is runningsudo supervisorctl statusInstall Laravel Echo and Socket IO clientnpm install –save laravel-echonpm install –save socket.io-clientAnd then in your bootstrap.js (I am using Vue js) register your Echoimport 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', });}Now check again how to listen for your events on specific channels.Following the documentation on Laravel Broadcasting we shared above, if you set your broadcastOn() method to return a new PresenceChannel (I will explain the particular case I did, but feel free to ask questions in case you need something else implemented. I find this to be of higher complexity than simply using a public channel, so we can scale down with no problems) then we want to listen for that channel on Javascript side (frontend).Here is a concrete example:I pushed an event onto a presence channel (I was dealing with surveys)public function broadcastOn(){return new PresenceChannel('survey.' . $this->survey->id);}2..After you push the event it will go through channels.php and in there we want to create authorization for this user (remember to return an array for presence channel authorization and not a Boolean)Broadcast::channel('survey.{survey_id}', function ($user, $survey_id) {return ['id' => $user->id,'image' => $user->image(),'full_name' => $user->full_name];});3..then in my VueJs component that loads on the page I want to monitor I define a method that will be initiated from created() method on load: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();});},I obviously pulled some code out of the context here but I have this ‘users_viewing’ array to keep my current users that joined the channel.And that would be it really.Hope you were able to follow as I tried to be detailed as I can.Happy coding!Follow me on TwitterAdd me on LinkedIn. More details

Leave a Reply