skip to Main Content

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


  1. 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:

    • Laravel Server: which hosts your Laravel application
    • Socket.IO server: which provides the sockets

    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:

    • ioredis: allows Node.js to interact with the running Redis instance
    • socket.io: allows you to create Socket.IO server
    • express: allows you to create an HTTP server. This is useful in our case because we’ll be exposing the socket server over HTTP using this package.

    You can install all these dependencies by running the following command:

    npm install ioredis socket.io express
    

    Now we need to create the Socket.IO server and expose it, here’s an implementation with comments:

    const express = require("express");         // include express
    const { Server } = require("socket.io");    // include the Server class from Socket.IO
    const { Redis } = require("ioredis");       // include the Redis class
    
    // instantiate an express app
    const app = express();
    const http = require("http");
    
    // create an HTTP server
    const server = http.createServer(app);
    
    // create a Socket.IO server that uses the previously declared HTTP server
    // and allow it to be accessible from any origin, and restrict it so that it
    // only accepts GET and POST requests
    const io = new Server(server, {
        cors: {
            origin: "*",
            methods: ["GET", "POST"],
        }
    });
    
    // instantiate an object to interact with Redis
    const redis = new Redis();
    
    // subscribe to all PUBLISH events done in Redis
    redis.psubscribe("*");
    
    // the on() method is used to listen to different events from Redis
    // whenever a new message is published into Redis using the PUBLISH command
    // this is what the "message" event means
    // a "message" event is triggered everytime Laravel dispatches a broadcastable event, we'll come to that later
    redis.on("pmessage", function (pattern, channel, message) {
        // just log the message
        console.log('Message Received: ' + message);
        console.log('Channel: ' + channel);
    
        // parse the message 
        message = JSON.parse(message);
    
        // broadcast the message to the subscribed clients
        server.emit(channel + ':' + message.event, message.data);
    });
    
    
    // the "connection" event is triggered every time there's a new client that
    // subscribed to the Socket.IO server
    io.on("connection", function (socket) {
        console.log("New connection")
    
        // the "data" event is triggered every time the socket receives incoming data
        socket.on("data", function (data) {
            console.log("Received data: " + data);
        });
    });
    
    // expose the Socket.IO server through HTTP port 6001
    server.listen(6001);
    
    

    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 the BROADCAST_DRIVER as follows:

    BROADCAST_DRIVER=redis
    

    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 called orders. In this case, within your blade template this is how you will listen to this event:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.5/socket.io.min.js"></script>
    <script>
    // don't forget to replace 127.0.0.1 with your own server address, if you're not on localhost
    const socket = io("http://127.0.0.1:6001");
    
    // this event fires when the client connects successfully to the socket server
    socket.on("connect", function() {
        console.log("connected to socket");
    });
    
    // listen to the OrderUpdated event on the orders channel
    socket.on("orders:OrderUpdated", function(e){
        console.log(e)
    });
    </script>
    

    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:

    socket.on("private-orders:OrderUpdated");
    

    The same goes for presence channels, just prefix with presence-.

    Here’s what happens:

    • Laravel broadcasts a message using the Redis broadcaster
    • The broadcasting process involves making a PUBLISH command to Redis that contains the message data
    • The Socket.IO server is observing Redis for any PUBLISH command, and so when a message comes the pmessage event is triggered.
    • Inside the call back to the pmessage event, Socket.IO broadcasts the message to all subscribers on the specified channel.
    Login or Signup to reply.
  2. 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. The index.php file shows how you can currently design a simple WebSocket server with PHP-CLI.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search