Home > Software design >  How to apply hasMany relation from Laravel Model in inertia ReactJs
How to apply hasMany relation from Laravel Model in inertia ReactJs

Time:09-20

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.

CodePudding user response:

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]);
    }
  • Related