我正在使用 Laravel Echo 将事件从服务器广播到客户端。
该应用程序是一个论坛,用户可以在其中创建主题帖子。
这是创建新帖子和分派事件的受控方法代码。
$post = Post::create([
'user_id' => 1,
'topic_id' => request('topic_id'),
'body' => request('body'),
]);
// Fetch the post we've just created, with the relationships this time
$post = Post::with('user', 'topic')->find($post->id);
// Broadcast the event
event(new PostCreated($post));
这是事件类:
class PostCreated implements ShouldBroadcast
{
public $post;
public function __construct(Post $post)
{
$this->post = $post;
}
public function broadcastOn()
{
return new Channel('topics.' . $this->post->topic_id);
}
}
最后,这里是前端拦截事件的地方:
Echo.channel('topics.' + this.topic.id)
.listen('PostCreated', (e) => {
this.posts.push(e.post);
});
问题是我似乎无法从前端user
的方法访问该属性。listen()
console.log(e.post.user) // Undefined
如果我做一个console.log()
帖子,我可以看到Post
(user_id, topic_id, body, created_at, updated_at) 的属性,但它没有显示在事件发送之前在控制器中预先加载的user
或属性。topic
这些属性可以从事件类本身访问:
// In the __construct() method of the PostCreated event
echo $this->post->user->name; // Works, the name is echo'd
...但是在广播事件时不知何故不会发送到前端。
如何确保user
和topic
属性连同帖子本身一起发送给客户端?