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

Laravel递归遍历分类报错:Attempt to read property 'id' on bool

问题解决:Laravel递归分类报错「Attempt to read property 'id' on bool」

核心错误点

递归调用视图时传递的参数错误,导致后续遍历的不是子分类集合,而是单个模型实例,进而引发遍历和属性读取异常。

具体修正步骤

  1. 修正递归视图的传参
    在parent_categoriest_loop.blade.php中,递归调用时应传递子分类集合$child->childrens,而非单个模型$child:
@foreach($childrens as $child)
    <tr>
        <td><a href="{{ route('blog_category.edit', $child->id) }}"><span style="font-size:12px">——</span> {{$child->name}}</a></td>
        <td>{{$child->created_at->format('d.m.Y')}}</td>
        <td>
            <a href="{{ route('blog_category.edit', $child->id) }}"><i class="fa fa-pencil"></i></a>
        </td>
    </tr>

    @if(count($child->childrens))
        <!-- 修正:传递子分类集合而非单个模型 -->
        @include('ecommerce::admin.blog_category.loop.parent_categoriest_loop', ['childrens' => $child->childrens])
    @endif
@endforeach
  1. 可选优化:控制器查询逻辑
    如果parent_id字段为整数类型(通常父分类的parent_id为0或null),原查询where('parent_id', '')可能不符合数据库实际存储规则,建议根据实际情况调整:
// 若parent_id为null表示父分类
$categories = BlogCategory::whereNull('parent_id')->paginate(10);

// 若parent_id为0表示父分类
// $categories = BlogCategory::where('parent_id', 0)->paginate(10);
  1. 可选优化:预加载关联避免N+1查询
    为提升性能,查询父分类时预加载子分类关联:
$categories = BlogCategory::whereNull('parent_id')
    ->with('childrens')
    ->paginate(10);

错误原因说明

原代码递归时传递['childrens' => $child],导致下一层视图的$childrens变量变为单个BlogCategory模型实例,而非子分类集合。当视图执行@foreach($childrens as $child)时,Laravel内部处理单个模型会返回布尔值,后续读取$child->id就会触发「Attempt to read property 'id' on bool」错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:23:25