Laravel 5: Broadcasting – Using Laravel Events (Laravel 5.2, no Pusher)

Laravel 5: Broadcasting – Using Laravel Events (Laravel 5.2, no Pusher)


This is a Laravel native way of broadcasting app events to clients.
It uses Redis of course, but all is abstracted to familiar Laravel coding.
NOTE:
This way uses Redis, Ioredis and Socket.io – but it does without paid Pusher service.

In this Laravel 5.2 way of broadcasting, you do not have versatility Laravel Echo offers, like PrivateChannel and PresenceChannel. You can emulate that by auto appending/preppending of dynamic elements, like e.g. order number etc and then dynamically crafting channel name in client (html) – but that is about it.
I was not able to find any easy, Laravel offered authorization routine, to keep user in, or out.
Of course we have socket and Redis pub/sub to fiddle with here, to try to accomplish same.

 

Attention
All background processes must run for this to work.
See here.

 

Phase 1: make sure all dependencies are available
Step 1: install, or make sure these are already available
node

See here how.

To check if available, type into command prompt, or console:

predis

To install, open console/command prompt and go inside of your Laravel project and type in this:

To check, if installed, try to install again.

socket.io

To install, open console/command prompt and go inside of your Laravel project and type in this:

To check, if installed, type in:

ioredis

To install, open console/command prompt and go inside of your Laravel project and type in this:

To check, if installed, type in:

Step 2: setup broadcasting driver

Setup broadcasting driver in .env file:

Check all available drivers in: /config/broadcasting.php

 

Phase 2: Fire Event
Step 1: prepare event file/class

In console/command prompt, from inside of Laravel project run this code:

SocketTesterEvent this is event name, it can be anything. Best if describes its job.

Event file is placed in: /app/Events category.

Make sure, you implemented ShouldBroadcast in SocketTesterEvent, like this:

It is not done by default.

Also ShouldBroadcast must be imported:

Step 2: fire and event

This can be fired in Route, but the best place for it in Controller, where you do something, that require broadcasted event to be fired. It can be done e.g. like this:

Using event object, you can pass (where I have ‘John Doe’) – just about anything:

  • id
  • some arbitrary data
  • even some other object, e.g. order object, or user object etc.

Additional info – how to fire event:

  1. dependency injection – inject event dispatcher (dependency injection), for examples look into:
  2. Event::fire() – here you use Facade – read more here
  3. global – function event()
Remember to import event object (use) on top of Controller, you are firing it in.

In our case, since we use:

.. we have to import:

Just see controller Welcome on top.

Phase 3: catch event on server and prepare for broadcast

Even fired in phase 2 can be caught on server by our SocketTesterEvent.

It can be structured properly for broadcasting.

Each public property will be picked up by Laravel and passed to channel defined in method: broadcastOn()

And here is our full SocketTesterEvent:

Channels, that can be used in method broadcastOn():

  • channel can be hardcoded, e.g.: return [‘test-channel’] – but this use is not recommended
  • Channel: public channel
  • PrivateChannel
  • PresenceChannel – this is a private channel with capacity to show, who is on the channel/page

 

Phase 4: broadcast event to clients (browsers)

Event method broadcastOn() passes data to node server.

Our server will reside in project’s root folder in file: socket.js.

Here is its code:

NOTE:
Above server has to be on, for sockets to work.
For development, you may just use command in console inside of project root directory:

to activate it.
You may also try to put it into scheduler.
I live project, it is better to run it as background process overseen by Supervisor, or Forever script.
For more see this checklist. Scroll to section describing sockets: “Checklist 4: Sockets”.

 

Phase 5: capture event in client (browser) and process it

Laravel pushes Vue, but I think jQuery can do same and it has better DOM objects manipulation tooling.
And there is interconnected jQueryUI and jQueryMobile to supplement, whatever jQuery cannot do.
OK jQueryMobile mobile is inferior to Bootstrap due to its heavy use of markup (which makes browser’s code very heavy).

So, I prefer jQuery, but you may stick to Vue.

Anyway, example below is jQuery.

Now, an event fired by Laravel can be pushed by servers to user’s browsers.

 

Laravel 5: Broadcasting – Things to Remember

Laravel 5: Broadcasting – Things to Remember


NOTE:
socket.io refuses to work in SSL mode on localhost under self-signed certificate, so either get some cert, or enable SSL for live only.
There are some other ways proposed on the net, but I was not able to make them work consistently, but I am hardly an authority in this department.

NOTE 2:
If you have any errors, check small stuff first, like misspelling, route pointing in wrong direction, before you start to despair.

NOTE 3:
If you use queues (except for sync) – you must remember to have “queue:listen” daemon running.
Check here how.

 

Socket.Io – Working Chat and General Stuff

Socket.Io – Working Chat and General Stuff


Socket.io allows for PHP based system to have server pushing data to client without request from client.

Most of that stuff below needs node.js installed on your server.

If you work on Windows just get Windows installer and add node to your Environment Variable path, to make it global.

Similar operation describing registering Composer with EV path is described here.


Socket.Io
Checking version

Same way you can check all stuff installed via np, like: express, ioredis etc.

Installation

Socket.io can be downloaded from here.

It can be installed using node.js npm, like this:

It is good to use ‘–save’ flag to add socket.io to dependencies list in your project package.json file, to keep it up to date with other stuff you are using, or you are about to use.

Usual socket project structure

Socket client

You need a socket.io client, which your project will pull into user’s browser
Something like:

If you do not want to use socket.io CDN (content delivery network) hosted client script, you can download version from here and serve it from your own server, or some other CDN.

Socket server worker

This is usually an index.js file, which is being activated via console command:

This file is a place where you bootstrap and fire all needed elements, like:

  • express framework
  • socket.io and all its channels, connections and broadcasting
  • html/template file (called, when accessing defined port)
  • define a port app is going to be listened on
  • etc.

When bootstrap is neatly tied, you can listen to your app in browser, by listening to defined port like this:

 

Sample Chat

Socket.io home page have chat demo here.

Unfortunately demo does not work.

In downloadable package below, you will find fixed version of that chat.
Of course, full credit goes to creators – I just fixed  few little things.

Edit 2018-03-18: demo works now and they added nice whiteboard.

zip

In archive you will find a drop-in package.
What it means is that all you have to do is:

  1. unzip
  2. drop content of folder /b8 (in archive) to your localhosted location
  3. change ‘b8’ in index.html file to your own localhosted location/domain, e.g. /mychat
  4. you need internet access (dependencies: botstrap, socket client, jquery)
  5. node dependencies: socket.io and express are already in zipped package
  6. open command prompt (windows) or console and go inside of your ‘mychat’ directory (or some other you are using)
  7. type is: node index.js – keep console open
  8. navigate in your browser to: mychat:3000

… and you have working chat open.

Now you can open another window with chat (or two) and see how posted stuff gets passed via sockets between browser windows. Same it would work between people in remote locations.

Here, you can find some nice socket.io cheat-sheet. Thanks Alex.
Just is case, it is also accessible here: socket-cheatsheet

 


Redis

If you wish to store some data, you can use Laravel’s Swiss army knife: Redis (queues, broadcasting, cache, data storage etc.)
More about Redis – here.

 


Redis.Js

There is also Redis API (client) called Redis.Js, that is a great way to work with Redis from within Socket.Io code.
You can find it here.

When installing, it is good to add it as dependency to your package.json like this (note –save):

This will update your package.json.

You need to have Redis installed on your system to use above wrapper (API)!
Other Redis clients

Find the all here.

Also, you may look at ioredis instead of redis.js

 


Express JS Framework

You will need this JS framework to work with sockets.

You can install it like this:

Again, ‘–save’ will add it to package.json as dependency.