I get the error
TypeError: Cannot read property ‘name’ of undefined”
if I go to deep in the object.
Timeline.vue
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="card card-default">
<div class="card-header">Timeline</div>
<div class="card-body">
<post v-for="post in posts" :key="post.id"></post>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import Post from './Post.vue'
export default {
data () {
return {
posts: []
}
},
components: {
Post
},
mounted() {
this.$http.get('/posts').then((response) => {
console.log(response.body)
this.posts =response.body
})
}
}
</script>
post.vue
<template>
<div class="media">
<div class="media-left">
</div>
<div class="media-body">
<strong>test</strong>
<strong>{{ post.user.name }} </strong>
</div>
</div>
</template>
<script>
export default {
props: [
'post'
]
}
</script>
Then why I get the error? I suppose some problem with {{ post.user.name }}.
/posts
route. But if I had to guess, you're not loading the post user relation. So you should probably use eager loadingPosts::with('user')->get()
in your controller. When you're writing$post->user->name
in PHP, Laravel makes sure the user is loaded on the fly, but if you return a JSON response in your controller without the loaded user, the client JS code can't load that relation data. – Bogdan