I am trying to display comments that are related to individual posts from the db. Displaying the comments with that post inside my React component (inertia), using eloquent relations in Laravel.
public function show()
{
$posts = Post::all();
return Inertia::render('Posts', ['posts' => $posts]);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
{props.posts.map((post, key) => {
console.log(post.comments);
return (
<div key={key}>
{post.title}
<ul>
// map of post.comments (with hasMany relation)
</ul>
</div>
)
})}
When logging inside my map of posts i receive a value of undefined.
you need to load the comments relation before sending it to inertia
public function show()
{
$posts = Post::with('comments')->get();
return Inertia::render('Posts', ['posts' => $posts]);
}