Maria
Maria

Reputation: 760

Laravel Vue - Get Eloquent on json response

I am trying to build a basic Laravel Vue comment system in order to learn both.

Now i am trying to display all the comments on a specific Post Article.

My controller returning the json_response.

public function comments(Post $post)
{
    return response()->json(
        $post->comments
    );
}

Everything work fine i get the following json response with Axios get method.

[
  {
    "id":1,
    "post_id":1,
    "user_id":1,
    "body":"Post Comment 1",
    "created_at":null,
    "updated_at":null,
    "deleted_at":null
  },
  {
    "id":2,
    "post_id":1,
    "user_id":1,
    "body":"Post comment 2",
    "created_at":null,
    "updated_at":null,
    "deleted_at":null
  }
]

I am displaying all the data with Vue but i am not sure how can i get hte relation eloquent i have on Comments and Users Models.

In Blade i can display the user if I return my response as data in a View like this:

@foreach($post->comments as $comment)

   {{ $comment->user->username }}

@endforeach

How can I pass the relation of user with comments in my json response to get the user of the comment, from the user_id value?

Upvotes: 3

Views: 224

Answers (1)

Maria
Maria

Reputation: 760

I manage to solve with help from Laracasts.

I have to change my response to

public function comments(Post $post)
{
    return response()->json(
        $post->comments->load('user');
    );
}

Upvotes: 4

Related Questions