Laravel递归遍历分类报错:Attempt to read property 'id' on bool
问题解决:Laravel递归分类报错「Attempt to read property 'id' on bool」
核心错误点
递归调用视图时传递的参数错误,导致后续遍历的不是子分类集合,而是单个模型实例,进而引发遍历和属性读取异常。
具体修正步骤
- 修正递归视图的传参
在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
- 可选优化:控制器查询逻辑
如果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);
- 可选优化:预加载关联避免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
相关产品推荐
相关产品推荐

