mstnorris
308
124
General

Step by Step Guide to Installing Socket.io and Broadcasting Events with Laravel 5.1

Posted 3 years ago by mstnorris

I've decided to put together a guide to help others in setting up socket.io within their projects. I hope you find this resource useful.

A big big shout out goes to @toniperic for helping me get socket.io up and running. You can view the original article where I got some of the information from; this guide builds upon it drastically, fills in the gaps, and is brought it up to date.

Please excuse any mistakes in this walkthrough, the Markdown wasn't being parsed correctly while I wrote it. I will edit it in situ within the Laracasts Forum when I spot errors. If you feel I should elaborate anywhere or amend anything please let me know below.

~~At the time of writing this (3 Jun 2015) Laravel 5.1 hasn't been released. It is due for release on 9 Jun 2015 so it certainly isn't long to go. I thought I'd get a head start on the game and put together this guide from different sources I found online.~~

In this walkthrough I'll assume you're using Laravel Homestead.

Prerequisites

Laravel Homestead already includes Node and Redis but just to check that they are installed and working correctly.

  1. SSH into your Homestead VM

  2. run node -v

    You will see something like "v0.10.33"

  3. run redis-cli ping

    You should see "PONG"

Create a New Project

  1. You will need to get the latest version of Laravel and depending on when you read this you will have to do one of the follow.

Using composer like so:

  • composer create-project laravel/laravel your-project-name dev-develop (to get the very latest release [may be unstable])
  • composer create-project laravel/laravel your-project-name

Or using the laravel new command:

  • laravel new your-project-name
  1. Edit your /etc/hosts file on your host OS.

    Add the line

  • "192.168.10.10 your-project-name.app"
  1. While SSH'd into Homestead run
  • serve your-project-name.app /home/vagrant/Code/path/to/public/directory 80
  1. Staying SSH'd into Homestead
  • cd your-project-name

Install packages

  1. npm install express ioredis socket.io --save

    Your package.json file will look like

{
  "private": true,
  "devDependencies": {
    "gulp": "^3.8.8",
    "laravel-elixir": "*"
  },
  "dependencies": {
    "express": "^4.12.4",
    "ioredis": "^1.4.0",
    "redis": "^0.12.1",
    "socket.io": "^1.3.5"
  }
}
  1. composer require predis/predis

    The require part of your composer.json file will look like

"require": {
    "laravel/framework": "5.1.*",
    "predis/predis": "^1.1@dev"
},

Creating the Event

  1. php artisan make:event EventName

    Open up your newly create EventName.php event class found within the app/Events directory.

  2. Make sure that it implements ShouldBroadcast

class EventName extends Event implements ShouldBroadcast
  1. The entire EventName.php class should look like
<?php namespace App\Events;

use App\Events\Event;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Queue\SerializesModels;

class EventName extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $data;

    public function __construct()
    {
        $this->data = array(
            'power'=> '10'
        );
    }

    public function broadcastOn()
    {
        return ['test-channel'];
    }
}

Setting up the Views

  1. Create a new view master.blade.php within the resources/views/layouts directory.
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FiveOne Socket.io</title>
</head>
<body>
@yield('content')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
@yield('footer')
</body>
</html>
  1. Create a second view that extends the master view above. I've called it test.blade.php. Put this in the resources/views directory.
@extends('layouts.master')

@section('content')
    <p id="power">0</p>
@stop

@section('footer')
    <script src="{ { asset('js/socket.io.js') } }"></script>
    <script>
        //var socket = io('http://localhost:3000');
        var socket = io('http://192.168.10.10:3000');
        socket.on("test-channel:App\\Events\\EventName", function(message){
            // increase the power everytime we load test route
            $('#power').text(parseInt($('#power').text()) + parseInt(message.data.power));
        });
    </script>
@stop

Routing

  1. Set up three routes like so. Add them to your app/Http/routes.php file.
Route::get('/', function() {
    // this doesn't do anything other than to
    // tell you to go to /fire
    return "go to /fire";
});

Route::get('fire', function () {
    // this fires the event
    event(new App\Events\EventName());
    return "event fired";
});

Route::get('test', function () {
    // this checks for the event
    return view('test');
});

Create the socket.js file

  1. Create a new file in your project root socket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel', function(err, count) {
});
redis.on('message', function(channel, message) {
    console.log('Message Recieved: ' + message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

Setting up Redis

As mentioned above Redis should already be installed but you just need to edit your .env file to tell Laravel to use the correct BROADCAST_DRIVER. Add the following line.

BROADCAST_DRIVER=redis

Starting the Servers

  1. Open two command line tabs and SSH into Homestead

    • cd into the root directory of your project

    • In the first tab, run node socket.js

      You should see "Listening on Port 3000"

    • In the second tab run redis-server --port 3001

      You should see a lot of output

Trying it out

  1. Open up two browser windows side by side and in the first one hit the URL:
  1. And in the second:
  1. Keep refreshing the first window and you should see the second page's content increment.

  1. You're all done!

  2. (I had to make this point (a) to make it an even 20! and (b) to kindly ask for your feedback. If follow this guide and you get stuck anywhere, or it doesn't make sense, or anything really, please let me know.)

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.