Laravel Vue - 在 json 响应中获得 Eloquent

Posted

技术标签:

【中文标题】Laravel Vue - 在 json 响应中获得 Eloquent【英文标题】:Laravel Vue - Get Eloquent on json response 【发布时间】:2019-11-16 19:34:47 【问题描述】:

我正在尝试构建一个基本的 Laravel Vue 评论系统来学习两者。

现在我正在尝试在特定的帖子文章上显示所有 cmets。

我的控制器返回 json_response。

public function comments(Post $post)

    return response()->json(
        $post->comments
    );

一切正常,我使用 Axios get 方法得到以下 json 响应。

[
  
    "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
  
]

我正在使用 Vue 显示所有数据,但我不确定如何在 CommentsUsers 模型上获得 hte 雄辩的关系。

在 Blade 中,如果我将响应作为数据返回到 View 中,我可以显示用户,如下所示:

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

    $comment->user->username 

@endforeach

如何在我的 json 响应中传递用户与 cmets 的关系,以从 user_id 值获取评论的用户?

【问题讨论】:

【参考方案1】:

我在 Laracasts 的帮助下设法解决了问题。

我必须改变我的回应

public function comments(Post $post)

    return response()->json(
        $post->comments->load('user');
    );

【讨论】:

以上是关于Laravel Vue - 在 json 响应中获得 Eloquent的主要内容,如果未能解决你的问题,请参考以下文章

Laravel/Vue - 传递数据:Json 嵌套值作为字符串

如何自定义 laravel api 的 json 响应并在 vuex 中显示它们

Laravel 响应::json 失败

使用自定义 json 响应进行 Laravel 验证

如何使用 vue axios 在 laravel 中解决 401 未授权响应

如何在laravel中返回json响应