我正在尝试在我的网站上实现通知功能。这是我的代码(希望我的方法是正确的)
- 创建一个名为notification的频道。{userId}(userId是经过身份验证的用户ID) - 例如,当我评论他的帖子时,触发通知广播的 NewComment 事件。{$ notification-> user_id}
这是我的代码:
public function newComment($post, $user){
$notification = new Notification; // this is notification model for my database table
$notification->type = 'new-comment';
$notification->notified_by = $user->id;
$notification->user_id = $post->owner->id;
$notification->save();
event(new NewNotification($notification));
}
NewNotification.php 事件
<?php
namespace App\Events;
use App\Models\Notification;
use App\Transformers\NotificationTransformer;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewNotification
{
protected $notification;
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Notification $notification)
{
$this->notification = $notification;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('notification.' . $this->notification->user_id);
}
public function broadcastWith(){
return fractal()->item($this->notification, new NotificationTransformer());
}
}
广播频道路线:
Broadcast::channel('notification.{userId}', function($user, $userId){
//comparing ($userId == $user->id) always turns true
});
订阅客户端的状态通道(使用Vue):
Echo.join('notification.' + this.user_id) //user_id is logged in user id
.listen('NewNotification', function(response){
console.log(response);
});
由于某种原因,从未调用过事件。我不知道我是否应该改变广播频道路由中的逻辑。我应该通过通知ID并检查通知 - > user_id === $ user-&gt; id。我已经通过这种方式进行了测试,但仍未在控制台中做出响应。
答案 0 :(得分:0)
我希望有人觉得这个答案很有用:
为了发起一个事件,事件类应该实现 ShouldBroadcast 类。
所以
class NewNotification{
//code here
}
成为
class NewNotification implements ShouldBroadcast{
// code here
}
不要忘记运行队列:如果您尚未设置自动作业,请收听