1👍
Try the below code,
I changed your controller index()
function to
use NorAm\UserManagement\Http\Requests\Request;
class myController{
public function index(Request $request){
$postId = $request->postId; // this should pass through you API.
$comment = Comment::with('post')->where('post_id',$postId)->get();
return new CommentResource($comment);
}
}
1👍
Your relationshipts seem to be correct, should be able to get all the Comments on a json structure with it’s related post nested like:
public function index()
{
return response()->json(Comment::with('post')->get());
}
Maybe you should check your database table structure and foreign keys
1👍
In CommentResource.php you should return the relationship when available
return [
...
'post' => new PostResource($this->whenLoaded('post')),
...
];
1👍
Am assuming you have post_id in your comments table. So for getting comments of the related to the particular post, you need to pass post_id(for which post you need comment) into your where.
So the query will be:-
Comment::with('post)->where('post_id',$postId)->get();
for fetching comments with related post.
Another way with your Post Model:-
And if you are fetching post and you need related comments with the post(your requirement).
then
in your model change your comments method with
public function comments(){
return $this->belongsToMany(Comment::class);
}
Post::with(comments)->get()
with this you can get post as well as comments