I attempted to integrate socket.io with Laravel, but was unsuccessful. I have been unable to find comprehensive documentation to facilitate this integration. I followed some documentation from Laracasts, but it appears to be outdated and did not resolve my issue. Could anyone provide guidance on properly integrating socket.io with Laravel? I eagerly await your response.
I have tried to integrate socket.io with Laravel, but to no avail.
2
Answers
The reason that you couldn’t find a decent guide for using Socket.IO with Laravel is that it’s not very common to use these two together, and there are many other better alternatives to be used with Laravel such as Pusher or Reverb.
However, and since I’ve been there before, I’ll explain to you briefly how you can connect Socket.IO and Laravel together, but please keep in mind that this is just a fundamental example, it shouldn’t be used in real-life projects without modifications.
We have two servers here:
First of all, you need to have Redis installed and running, Redis is important here because it’s used to pass messages between Socket.IO and Laravel (also called a
broker
).Create a separate Node.js project in a separate directory, and inside it install the following dependencies:
You can install all these dependencies by running the following command:
Now we need to create the Socket.IO server and expose it, here’s an implementation with comments:
Okay, let’s see what happens on the Laravel side. First of all, we need to set our broadcast driver to be Redis. To do this, open your
.env
and set theBROADCAST_DRIVER
as follows:And that’s all about it really, you don’t have to change anything else in your events classes. Just make sure that your events classes implement the
IlluminateContractsBroadcastingShouldBroadcast
interface.Let’s assume that we have an event called
OrderUpdated
that will be broadcast on a public channel calledorders
. In this case, within your blade template this is how you will listen to this event:Notice that if you’re broadcasting the event on a private channel, you have to prefix the channel name with the prefix
private-
in your blade code. For example:The same goes for presence channels, just prefix with
presence-
.Here’s what happens:
PUBLISH
command to Redis that contains the message dataPUBLISH
command, and so when a message comes thepmessage
event is triggered.pmessage
event, Socket.IO broadcasts the message to all subscribers on the specified channel.I’ve always found using a pure PHP solution pretty easy. Full disclaimer this is my repo. I’m in the process of updating/adding to the PHP interpreter source code in
C
to make the process even faster. Theindex.php
file shows how you can currently design a simple WebSocket server withPHP-CLI
.