You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel如何获取帖子的1条最新评论 调用last()方法报错求助

问题原因

你现在的报错本质是对字符串类型调用了只有集合/对象才有的last()方法,且逻辑方向搞反了:

  • 你遍历$post->comments拿到的每一个$comment本身就是单条评论实例
  • $comment->body是单条评论的内容字段,本身就是字符串,没有last()方法可以调用
  • 你要的是取「所有评论里的最新1条」,完全不需要遍历所有评论

解决方法

方案1:直接在模板中取评论集合的最新项(快速修复)

直接对$post->comments这个评论集合调用last()拿到最新评论实例,再取内容即可:

{{-- 先判断有没有评论,避免没有评论时报错 --}}
@if($post->comments->isNotEmpty())
    {{ $post->comments->last()->body }}
@endif

方案2:新增关联优化性能(推荐)

如果项目里频繁需要取帖子的最新评论,直接在Post模型中新增一对一的最新评论关联,还能避免循环遍历、解决N+1查询问题:

  1. 先在Post模型中加关联方法
// app/Models/Post.php
public function latestComment()
{
    return $this->hasOne(Comment::class)->latest();
}
  1. 控制器查询帖子的时候预加载最新评论
// 控制器查询代码示例
$posts = Post::with('latestComment')->get();
  1. 模板直接调用即可
@if($post->latestComment)
    {{ $post->latestComment->body }}
@endif

内容的提问来源于stack exchange,提问作者adeala ademola

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 23:33:03