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

Laravel HttpClient Post请求中数组参数传递失败问题排查

问题:Laravel Http客户端Post请求中嵌套数组TL未被正确传递

我用Laravel的Http客户端写了一个从Blade表单存储数据的Post请求函数:

$store = Http::withHeaders([
        'Content-Type' => 'application/json',
        'Authorization' => $token,
    ])->post('http://example.com/api/Order/', [
        'Key' => 1167722,
        'No' => "12",
        'TL' => [
            'Dtl' => "",
            'Code' => "Screw Hex",
            'IsDetail' => true,
            "DTL" => [],
            ]
        ]);

return $store;

但返回的响应显示TL数组是空的:

{"Key":1167722,"No":"12","TL":[]}

我试过用json_encode包裹TL数组,还有'TL[Dtl]' => 722的写法,都没解决问题。


解决方法

1. 确认目标API的参数命名规则

先检查目标APIhttp://example.com/api/Order/是否对键名大小写敏感。你传递的TL里包含"DTL" => [],而响应中TL为空,可能API期望的键名是小写格式(比如dtl而非DTL),或者有其他命名规范,需和API文档对齐。

2. 使用postJson方法简化JSON请求

Laravel的postJson方法会自动设置Content-Type: application/json头,并正确序列化数组为JSON格式,替代手动设置头的方式:

$store = Http::withHeaders([
        'Authorization' => $token,
    ])->postJson('http://example.com/api/Order/', [
        'Key' => 1167722,
        'No' => "12",
        'TL' => [
            'Dtl' => "",
            'Code' => "Screw Hex",
            'IsDetail' => true,
            "DTL" => [],
        ]
    ]);

return $store;

3. 手动序列化请求体

如果postJson仍不生效,尝试手动将整个请求数据序列化为JSON字符串后发送:

$payload = json_encode([
    'Key' => 1167722,
    'No' => "12",
    'TL' => [
        'Dtl' => "",
        'Code' => "Screw Hex",
        'IsDetail' => true,
        "DTL" => [],
    ]
]);

$store = Http::withHeaders([
        'Content-Type' => 'application/json',
        'Authorization' => $token,
    ])->post('http://example.com/api/Order/', $payload);

return $store;

4. 查看请求日志排查问题

开启Laravel请求日志,确认实际发送的请求内容是否符合预期:

Http::log(); // 开启请求日志,需确保日志配置正常

然后查看storage/logs/laravel.log中的请求详情,对比发送的数据与API要求的格式是否一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:54:18