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

Laravel 8中API数据循环报错:Attempt to read property 'id' on bool

问题排查与解决

核心原因

  1. 数据类型不匹配:你用json_decode($countries, true)将API返回转为关联数组,但Blade模板里却用对象语法$country->id访问属性,这本身不符合语法规则——数组需用$country['id']访问。
  2. API请求或返回异常:你给file_get_contents加了@错误抑制符,导致请求失败时(比如网络错误、API地址无效)不会抛出错误,而是返回false。后续json_decode(false, true)得到null,如果直接将未校验的$countriesArray['data']传入模板循环,就会出现遍历非数组的情况,最终导致$country变成布尔值,触发“Attempt to read property 'id' on bool”错误。

解决步骤

1. 移除错误抑制,排查请求问题

删掉file_get_contents前的@,让请求失败时直接抛出错误,方便定位根源:

$countries = file_get_contents('https://external../api/countries'); 

2. 严格校验API返回数据

在使用数据前,先校验请求是否成功、返回结构是否符合预期:

// 初始化空数组,避免模板循环报错
$countryList = [];

// 检查请求是否成功
if ($countries !== false) {
    $countriesArray = json_decode($countries, true);
    // 校验返回的success状态和data字段是否为数组
    if (isset($countriesArray['success']) && $countriesArray['success'] && isset($countriesArray['data']) && is_array($countriesArray['data'])) {
        $countryList = $countriesArray['data'];
    }
}

// 将校验后的数组传入模板
return view('your-template-name', compact('countryList'));

3. 模板使用对应语法访问数据

因为$countryList是关联数组,Blade循环时用数组索引访问:

<select>
    @foreach($countryList as $country)
        <option value="{{ $country['id'] }}">{{ $country['name'] }}</option>
    @endforeach
</select>

如果偏好对象语法,修改json_decode参数(去掉第二个true),将返回转为对象:

$countriesArray = json_decode($countries);
// 对应校验逻辑改为对象属性访问
if (isset($countriesArray->success) && $countriesArray->success && isset($countriesArray->data) && is_array($countriesArray->data)) {
    $countryList = $countriesArray->data;
}

此时模板里就可以用$country->id访问了。

4. 禁止直接使用未校验数据

永远不要直接将API返回的原始数据传入模板,必须先校验success状态和data的类型,否则API返回异常时(比如success为false、data是字符串),循环非数组会导致遍历出布尔值/字符串,触发属性访问错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:22:53