Laravel Echo事件中未定义的已加载模型
我正在使用Laravel Echo将事件从服务器广播到客户端 该应用程序是一个论坛,用户可以在其中创建主题帖子 下面是创建新post和调度事件的受控方法代码Laravel Echo事件中未定义的已加载模型,laravel,eloquent,laravel-echo,Laravel,Eloquent,Laravel Echo,我正在使用Laravel Echo将事件从服务器广播到客户端 该应用程序是一个论坛,用户可以在其中创建主题帖子 下面是创建新post和调度事件的受控方法代码 $post = Post::create([ 'user_id' => 1, 'topic_id' => request('topic_id'), 'body' => request('body'), ]); // Fetch the post we've just created, with the rel
$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);
});
问题是我似乎无法从前端的listen()
方法访问user
属性
console.log(e.post.user) // Undefined
如果我对帖子执行console.log()
,我可以看到post
的属性(用户id、主题id、正文、创建时间、更新时间),但它不会显示发送事件之前在控制器中加载的用户
或主题
属性
这些属性可以从事件类本身访问:
// In the __construct() method of the PostCreated event
echo $this->post->user->name; // Works, the name is echo'd
。。。但不知何故,当事件被广播时,它们并没有被发送到前端
如何确保用户
和主题
属性与帖子本身一起发送到客户端