mafortis
mafortis

Reputation: 7128

getting post author in laravel vue

In blade way when we have relation between posts and users we can retrieve post author like {{$post->user->name}} now I am using vue and I want to do the same like {{post.user.name}} but it doesn't return author info.

it gives me this errors in console:

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

TypeError: Cannot read property 'name' of undefined

code

<script>
    export default {
        data() {
            return {
                posts: []
            }
        },
        mounted: function() {
            this.load()
        },
        methods: {
            load: function() {
                axios.get('/api/posts')
                .then(
                    response => {
                        this.posts=  (response.data.posts);
                    }     
                )
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }
    }
</script>

any idea?

UPDATE

user model

public function posts()
    {
        return $this->hasMany(Post::class);
    }

Post model

public function User()
    {
        return $this->belongsTo(User::class);
    }

Controller

public function index()
    {
        $posts = Post::orderby('id', 'desc')->get();
        return response()->json([
            "posts" => $posts
        ], 200);
    }

Upvotes: 0

Views: 363

Answers (1)

Thamer
Thamer

Reputation: 1954

as I expect, you must return posts data like this :

Ps: update it with your own posts fields.

public function index()
    {
        $posts = Post::orderby('id', 'desc')->get();

         return $posts->map(function($post) {
            return [
                 'id' => $post->id,
                'title' => $post->title,
                'description' => $post->description,
                'user' => $post->user->name
            ];
        });
    }

and your component must be edited :

<script>
    export default {
        data() {
            return {
                posts: []
            }
        },
        mounted: function() {
            this.load()
        },
        methods: {
            load: function() {
                axios.get('/api/posts')
                .then(
                    response => {
                        this.posts=  (response.data);
                    }     
                )
                .catch(function (error) {
                    this.errors.push(error);
                    console.log(error);
                })
            }
        }
    }
</script>

Upvotes: 1

Related Questions