Great guide!! Thank you for taking the time to put it all together. Can't wait to give this a try.
Step by Step Guide to Installing Socket.io and Broadcasting Events with Laravel 5.1
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.
-
SSH into your Homestead VM
-
run
node -vYou will see something like "v0.10.33"
-
run
redis-cli pingYou should see "PONG"
Create a New Project
- 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
-
Edit your /etc/hosts file on your host OS.
Add the line
- "192.168.10.10 your-project-name.app"
- While SSH'd into Homestead run
-
serve your-project-name.app /home/vagrant/Code/path/to/public/directory 80
- Staying SSH'd into Homestead
-
cd your-project-name
Install packages
-
npm install express ioredis socket.io --saveYour 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"
}
}
-
composer require predis/predisThe require part of your composer.json file will look like
"require": {
"laravel/framework": "5.1.*",
"predis/predis": "^1.1@dev"
},
Creating the Event
-
php artisan make:event EventNameOpen up your newly create EventName.php event class found within the app/Events directory.
-
Make sure that it implements ShouldBroadcast
class EventName extends Event implements ShouldBroadcast
- 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
- 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>
- 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
- 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
- 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
-
Open two command line tabs and SSH into Homestead
-
cdinto the root directory of your project -
In the first tab, run
node socket.jsYou should see "Listening on Port 3000"
-
In the second tab run
redis-server --port 3001You should see a lot of output
-
Trying it out
- Open up two browser windows side by side and in the first one hit the URL:
- And in the second:
- Keep refreshing the first window and you should see the second page's content increment.



-
You're all done!
-
(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 or to participate in this conversation.