I'm trying to create a real-time notification system using Laravel as the client API and SPA for my interface, I use React as the interface, but for the example below I will use simple Vue.Js and the blade that I created. to get a working example.
So, overall, I have a route that fires the event, as shown in the following example:
Route::get('fire', function () {
$user = App\Models\User::find(1);
event(new App\Events\CampaignUploadedWithSuccess($user, 'testing a notification'));
return "event fired";
});
The event that it fires will look like this:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class CampaignUploadedWithSuccess implements ShouldBroadcast
{
protected $user;
public $notification;
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct($user, $notification)
{
$this->user = $user;
$this->notification = $notification;
}
public function broadcastOn()
{
return ['notifications-channel.' . $this->user->id];
}
}
So, I broadcast on the channel notification-channel.{userId}
Then I have a socket.js file that I run with node.
It looks like
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('notifications-channel.1', function(err, count) {
});
redis.on('message', function(channel, message) {
console.log('Notification Recieved: ' + message);
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
console.log('Listening on Port 3000');
});
using node socket.js
starts the server, and triggering the event does what I want, as shown below:

Happy Days! I broadcast to the channel.
, test.blade, Vue Socket.io
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
</head>
<body>
<h1>Notifications</h1>
<ul>
<li v-repeat="notification: notifications">@{{ notifications }}</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js"></script>
<script>
var socket = io('http://localhost:3000');
new Vue({
el: 'body',
data: {
notifications: []
},
ready: function() {
socket.on('notifications-channel.1', function(data) {
alert(data.notification);
});
}
});
</script>
</body>
</html>
, , -1 , . .
, , , socket.io, Laravel Redis.
. , , , , .