Odyssee
Odyssee

Reputation: 2463

Laravel API - Vue.js returning Posts with user

I am trying to learn Vue.js that consumes an API build with Laravel. The idea is simple, a user can make a post and a post can have comments. I can get the relationships working within laravel, but I can not figure out how to return the author name of the post or comment with Vue.js.

When using the blade templating engine I use something like this in a foreach loop for returning the Author name:

{{ $post->user->name }}

When I return the posts trough an API I get don't get any user information, except for the user id. How can I get the user information that belongs to this post?

{
  "message": "Success",
  "data": [
    {
      "id": 1,
      "body": "test body 1",
      "user_id": "1",
      "created_at": "2016-09-16 10:22:57",
      "updated_at": "2016-09-16 10:22:57"
    }
  ]
}

<script>
  export default {
        /*
         * The component's data.
         */
         data() {
            return {

                posts: [],

            };
        },

        /**
         * Prepare the component.
         */
         ready() {

            this.getPosts();

        },

        methods: {

            /**
             * Get Posts.
             */
            getPosts: function() {
                this.$http.get('/api/wall/posts')
                    .then(response => {

                        this.posts = response.data.posts;

                    });
            }

        }
    }
</script>

public function getPosts($id = null)
    {
        if (!$id){
            $data = Post::all();
            $message = 'Success';
            $code = 200;
        } else {
            $data = Post::FindOrFail($id);
            $message = 'Success';
            $code = 200;
        }
        return Response::json(['message' => $message, 'data' => $data], $code);
    }

Upvotes: 1

Views: 578

Answers (1)

ABDEL-RHMAN
ABDEL-RHMAN

Reputation: 3014

You may use eager loading for that:

Post::with('user')->FindOrFail($id);

Upvotes: 3

Related Questions