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

Laravel Blade多态关联属性读取失败问题排查与解决

问题:Laravel多态关联调用关联属性报“Attempt to read property "title" on null”错误

模型关联定义

Comment模型

public function commentable(): MorphTo
{
    return $this->morphTo();
}

Post模型

public function comments(): MorphMany
{
    return $this->morphMany(Comment::class, 'commentable')->notReply();
}

查询代码

通过以下代码获取关联文章的评论:

$comments = Comment::blog()->with('commentable')->latest()->paginate(50);

异常现象

在Blade模板循环中,使用dd($comment->commentable->title)能正常返回文章标题,但直接输出$comment->commentable->title时,抛出错误:Attempt to read property "title" on null。即使在Comment模型中新增方法封装属性调用,直接调用方法仍报错,用dd则正常返回。

Blade代码示例:

@foreach($comments as $key=> $comment)
    {{ dd($comment->commentable->title) }} // 正常返回文章标题
    {{ $comment->commentable->title }} // 报错Attempt to read property "title" on null
@endforeach

Comment模型新增封装方法:

public function postTitle(): ?string
{
    return $this->commentable->title;
}

已解决方案

问题根源是存在关联文章已被软删除的评论。Laravel的with()预加载默认不会包含软删除的模型,导致这类评论的commentable属性为null,循环到该条评论时触发报错。

可选解决方式:

  • 检查数据库中评论对应的commentable_type和commentable_id记录,清理关联模型已删除的无效评论
  • 若需要显示软删除的关联模型,在关联定义中加入withTrashed():
public function commentable(): MorphTo
{
    return $this->morphTo()->withTrashed();
}
  • 在模板中添加空值判断避免报错:
{{ $comment->commentable?->title }}
  • 查询时直接过滤掉关联模型已被软删除的评论:
$comments = Comment::blog()
    ->whereHas('commentable')
    ->with('commentable')
    ->latest()
    ->paginate(50);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:53:27