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

使用Http::post调用API,Laravel报数组偏移量访问int类型值错误求助

解决Laravel调用API时的"Trying to access array offset on value of type int"错误

1. 对齐Postman的请求参数格式

Postman能正常请求,说明你当前代码的参数格式可能和Postman不一致,重点检查chapters字段:
多数API要求chapters是数组包裹的对象集合,而你当前传的是单个关联数组。如果Postman中chapters是[{"id":3,"name":"Aljabar","count":10}]这种格式,代码要改成:

$response = Http::post('https://url.id/api/tryout/check', [
    'category_id' => 0,
    'platform' => 'platform',
    'is_unique' => false,
    'chapters' => [
        [
            'id' => 3,
            'name' => "Aljabar",
            'count' => 10,
        ],
    ],
]);

2. 正确处理API响应

直接返回Laravel的Response对象可能导致框架转换时出错,要先解析响应并做错误校验:

$response = Http::post('https://url.id/api/tryout/check', [
    // 这里放调整后的参数
    'category_id' => 0,
    'platform' => 'platform',
    'is_unique' => false,
    'chapters' => [
        [
            'id' => 3,
            'name' => "Aljabar",
            'count' => 10,
        ],
    ],
]);

// 先判断请求是否成功
if ($response->failed()) {
    return response()->json(['error' => '请求失败', 'status_code' => $response->status()], $response->status());
}

// 解析JSON响应
$responseData = $response->json();

// 校验返回格式,避免后续访问出错
if (!is_array($responseData) && !is_object($responseData)) {
    return response()->json(['error' => 'API返回格式异常'], 500);
}

return response()->json($responseData);

3. 排查API返回内容

如果参数格式没问题,可先打印原始响应确认API返回:

// 在处理响应前添加
dd($response->body());

如果返回的是单个整数(比如错误码),说明API返回了错误状态,需要根据状态码排查参数合法性、权限等问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:09:25