我写了一个小laravel / JavaScript应用程序,我可以通知用户。目前所有用户都会收到通知,但我想通知特定用户。
到目前为止我构建了这个:
Laravel Event class:
class NotificationSent implements ShouldBroadcast
{
use SerializesModels;
public $notifications;
public $user;
public function __construct(array $notifications, $user)
{
$this->notifications = $notifications;
$this->user = $user;
}
public function broadcastOn()
{
return ['notification-channel'];
// return ['notification-channel-'. $this->user->id];
}
}
我像这样开火,
# fire event to sent notification
event(new NotificationSent(
$notifications, $admin
));
我想在用户上激活事件($ admin包含用户模型)。
我的套接字服务器socket.js
// socket.js
var server = require('http').Server();
var io = require('socket.io')(server);
// class declaration
var Redis = require('ioredis');
// Redis UserSignedUp Channel
var redisUserSignedUp = new Redis();
// Redis NotificationSent Channel
var redisNotificationSent = new Redis();
redisNotificationSent.subscribe('notification-channel');
redisNotificationSent.on('message', function(channel, message) {
message = JSON.parse(message);
console.log(channel, message);
io.emit(channel + ':' + message.event, message.data);
});
server.listen(3000);
我的Event.js
var socket = io('http://192.168.3.125:3000'); // local
Vue.use(VToaster, {timeout: 5000})
new Vue({
el: '#app',
data: {
authID: $('#auth-id').val(),
},
mounted: function() {
// NotificationSent Event
socket.on('notification-channel-' + this.authID + ':App\\Events\\NotificationSent', function(data) {
// socket.on('notification-channel:App\\Events\\NotificationSent', function(data) {
console.log(data);
this.$toaster.info('Hi.');
}.bind(this));
},
});