Yashgupta
Yashgupta

Reputation: 211

how can i get user object in comment in laravel

i'm trying to get the post with the user,and posts comments but i also want commented user data. currently i'm getting userdata and comments related to post with this code but also want user object for comments. the code i'm using is in PostController.php

public function index()
{   
    $post=Post::orderBy('created_at','DESC')->with('user')->with('comments' )->get();
    return response()->json(["posts" => $post ]);
}

this is returning

enter image description here

i also set the relationship in models is there any way i can get user object inside comments object like this:

enter image description here

Thanks!

Upvotes: 0

Views: 217

Answers (1)

Mohammad
Mohammad

Reputation: 660

try this :

public function index()
{   
    $post = Post::orderBy('created_at','DESC')with(['comments', 'comments.user'])->get();
    return response()->json(["posts" => $post ]);
}

i hope help you

Upvotes: 1

Related Questions