1

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.

This is my PostController:
public function show()
    {
        $posts = Post::all();
        return Inertia::render('Posts', ['posts' => $posts]);
    }
My eloquent relation inside my Post model:
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
This array of posts is send to my react component, inside my props (props.posts):
{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.

Miss Def
  • 13
  • 2

1 Answers1

1

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]);
    }
RawSlugs
  • 520
  • 4
  • 11
  • 1
    Hi! Thank you! It helped me on my way. As a newbie, I did need some additional doc on predefining and loading relational data. It works now :) – Miss Def Sep 20 '22 at 14:03