Laravel 8中API数据循环报错:Attempt to read property 'id' on bool
问题排查与解决
核心原因
- 数据类型不匹配:你用
json_decode($countries, true)将API返回转为关联数组,但Blade模板里却用对象语法$country->id访问属性,这本身不符合语法规则——数组需用$country['id']访问。 - 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
相关产品推荐
相关产品推荐

