1
votes

I am having problem accessing eloquent's association from within VueJS component via props.

So am passing a model object to vue component, like this:

Comment model

public function post()
{
   return belongsTo('App\Post');
}

Comment controller

$comments = Comment::all()
return view('comments', ['comments' => $comments);

comment blade

<comment-index :comments="{{ $comments }}"></comment-index>

comment vue component

<template>
   <div>
      <table>
          <tr v-for="comment in comments">
             <td>{{ comment.message }}
             <td>{{ comment.post.title }} // post is undefined
          </tr>
      </table>
   </div>
</template>
<script>
    export default {
        props: ['comments'] 
    }
</script>

But if if I loop and dump the post in the controller, the post shows in the vue template:

$comments = Comment::all()

foreach($comments as $comment) {
   dump($comment->post->title);
}
return view('comments', ['comments' => $comments);
1

1 Answers

1
votes

Since you are using Vue on comment.blade the post is not lazy loaded while it is being lazy loaded when you access it via $comment->post->title on your controller.

From the Laravel docs:

When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property.

Since you are using Vue (client-side) to access post, lazy loading will not work and thus it is not loaded when you access it like this: {{ comment.post.title }} leading to it's value being undefined.

To solve this, you can eager load the comment post by doing this.

$comments = Comment::with('post')->get();

Also if you don't lazy load the comment's post and the comments grow larger, it may lead to some performance issue with N + 1 query problem.