2018-01-29 01:16

Laravel Vue将用户详细信息添加到注释数组

I'm working on laravel comment system with vue js, and facing a problem when doing axios request. I need to receive an array as a response with all the comments for the post, but I would like to add user data to this array to get username and rest of users details to display.

public function show($id)
      $comments = Post::find($id)->comments;
      return $comments;



What I would need is:

[{"id":35,"user_id":1,"post_id":4,"parent_id":0,"commenttext":"test","created_at":null,"updated_at":null, "user":[User Data Here]}]

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doufu9836 doufu9836 3年前

    Use nested eager loading.

    $comments = Post::with('comments.user')->where('id', $id)->first()->comments;

    That should retrieve all comments with its user relationship.

    foreach($comments as $comment)
        echo $comment->user->id;

    Or I believe you can also do this. (Lazy Eager loading)

    $post = Post::find($id);
    $comments = $post->comments;
    点赞 评论 复制链接分享