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

Laravel控制器如何获取AJAX提交的JSON数组元素的id等字段值

问题原因

Laravel 解析前端提交的 JSON 数据时,默认会将 JSON 中的对象转为关联数组而非标准对象,因此你使用对象访问符 -> 读取字段会报错。

解决方法

方法1:直接使用数组语法访问(最简便)

把对象访问符替换为数组访问符即可,示例代码如下:

public function addOrders(Request $request) {
    // 读取单个字段
    $id = $request->sepet[0]['id'];
    $foodPrice = $request->sepet[0]['food_price'];
    $foodTitle = $request->sepet[0]['food_title'];

    return $id;
}

方法2:转为对象后使用对象语法访问

如果你习惯用对象语法读取字段,可以先将数组转为对象:

public function addOrders(Request $request) {
    // 把整个sepet数组转为对象集合
    $sepetItems = collect($request->sepet)->map(fn($item) => (object)$item);
    
    // 之后就可以用对象访问符读取
    $id = $sepetItems[0]->id;
    $foodPrice = $sepetItems[0]->food_price;
    $foodTitle = $sepetItems[0]->food_title;

    return $id;
}

批量写入数据库完整示例

如果要把sepet数组的所有条目写入数据库,建议先做数据校验,再循环插入:

public function addOrders(Request $request) {
    // 校验提交数据格式,避免非法参数
    $validated = $request->validate([
        'sepet' => 'required|array',
        'sepet.*.id' => 'required|integer',
        'sepet.*.food_price' => 'required|numeric',
        'sepet.*.food_title' => 'required|string',
        // 按需补充其他字段的校验规则
    ]);

    foreach ($validated['sepet'] as $item) {
        // 假设对应订单模型为Order,直接写入数据
        Order::create([
            'food_id' => $item['id'],
            'food_price' => $item['food_price'],
            'food_title' => $item['food_title'],
            // 补充其他需要写入的字段,比如用户id、订单号等
        ]);
    }

    return response()->json([
        'code' => 200,
        'msg' => '订单创建成功'
    ]);
}

注意:使用create方法写入数据前,请确保对应模型的$fillable属性已经配置了允许批量赋值的字段,避免触发Laravel的批量赋值防护机制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 06:03:03