6
votes

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 }}.

1
You should post the code executed from the /posts route. But if I had to guess, you're not loading the post user relation. So you should probably use eager loading Posts::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
Adding either the post array or one post as an example would help outSérgio Reis
Yes . I check localhost:8888/posts . It shows [{"id":1,"user_id":1,"body":"Necessitatibus cumque pariatur in excepturi.","created_at":"2018-04-20 07:48:56","updated_at":"2018-04-20 07:48:56","user":{"id":1,"name":"eunice","email":"[email protected]","created_at":"2018-04-05 08:20:13","updated_at":"2018-04-05 08:20:13"}},Erison Li
My post controller is below public function index(Request $request, Post $post) { return $post->with(['user'])->latestFirst()->get(); }Erison Li

1 Answers

2
votes

You need to pass the post prop in the template like so. otherwise it's undefined in the child component (post).

<div class="card-body">
    <post 
        v-for="post in posts" 
        :key="post.id"
        :post="post">
    </post>
</div>