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

报错Trying to access array offset on null(第49行),求PHP代码排查帮助

报错排查:Trying to access array offset on value of type null(第49行)

场景:实现客户发票打印功能,需展示客户购买商品的分类、商品名称、发票编号及日期,运行时触发上述报错。

出现错误的页面代码

@foreach($allData as $key => $item)
    <tr>
        <td> {{ $key+1}} </td>
        <td>{{ $item['category']['name'] }}</td>
        <td> #{{ $item['invoice']['invoice_no'] }}   </td>
        <td> {{  date('d-m-Y',strtotime($item['invoice']['date'])) }} </td>
        <td> {{ $item->due_amount }} </td>
        <td>
            <a href="{{ route('customer.edit.invoice',$item->invoice_id) }}" class="btn btn-info sm" title="Edit Data">  <i class="fas fa-edit"></i> </a>
            <a href="{{ route('customer.invoice.details.pdf',$item->invoice_id) }}" target="_blank" class="btn btn-danger sm" title="Customer Invoice Details">  <i class="fa fa-eye"></i> </a>
        </td>
    </tr>
@endforeach

错误原因分析

  • 关联数据为空:部分$item的category或invoice关联为null(比如商品未绑定分类、发票记录缺失),直接访问['name']、['invoice_no']等子字段时触发报错。
  • 关联未预加载:控制器查询$allData时未使用with()预加载category和invoice关联,导致部分数据的关联未被正确加载,返回null。
  • 数据完整性问题:数据库中存在无效的category_id或invoice_id,关联查询无法找到对应记录,返回null。

解决方案

  1. 添加空值安全访问:在Blade模板中使用PHP空安全运算符?->和空合并运算符??处理可能为null的关联:
@foreach($allData as $key => $item)
    <tr>
        <td> {{ $key+1}} </td>
        <td>{{ $item['category']?->name ?? '无分类' }}</td>
        <td> #{{ $item['invoice']?->invoice_no ?? '无发票号' }}   </td>
        <td> {{ $item['invoice']?->date ? date('d-m-Y', strtotime($item['invoice']->date)) : '无日期' }} </td>
        <td> {{ $item->due_amount }} </td>
        <td>
            <a href="{{ route('customer.edit.invoice',$item->invoice_id) }}" class="btn btn-info sm" title="Edit Data">  <i class="fas fa-edit"></i> </a>
            <a href="{{ route('customer.invoice.details.pdf',$item->invoice_id) }}" target="_blank" class="btn btn-danger sm" title="Customer Invoice Details">  <i class="fa fa-eye"></i> </a>
        </td>
    </tr>
@endforeach
  1. 预加载关联数据:在控制器中修改查询逻辑,预加载关联避免N+1查询并确保数据加载完整:
// 替换YourModel为实际模型类名
$allData = YourModel::with(['category', 'invoice'])->get();
  1. 修复数据完整性:检查数据库中相关记录,确保每个item的category_id和invoice_id对应有效存在的分类和发票记录,若允许为空则保持代码中的空值处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:05:22