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

Laravel+JQuery保存发票及商品至不同表报foreach错误求助

解决Laravel控制器中foreach循环的"Trying to get property of non-object"错误

我帮你排查了问题,核心原因是你对提交的items数据结构理解偏差了:你前端传过来的items是一个对象数组,每个元素都是包含完整商品字段的独立对象,但控制器里你错误地把$data(也就是$request->items)当成了带有item_name属性的单个对象来访问,这就触发了报错——数组根本没有->item_name这个属性呀!

修正后的控制器代码

把foreach循环改成遍历$data数组,每个元素就是一个完整的商品对象,同时补充几个关键细节:

public function store(Request $request) {
    // 保存发票主表数据
    $invoice = new Invoice();
    $invoice->inv_id = $request->inv_id;
    $invoice->inv_date_of_purchase = $request->inv_date_of_purchase;
    $invoice->inv_return_month = $request->inv_return_month;
    $invoice->inv_due_date = $request->inv_due_date;
    $invoice->inv_customer_name = $request->customername; // 注意!前端传的是customername,不是inv_customer_name
    $invoice->inv_customer_gstin = $request->inv_customer_gstin;
    $invoice->inv_customer_state = $request->inv_customer_state;
    $invoice->inv_customer_bill_address = $request->inv_customer_bill_address;
    $invoice->save();

    // 处理商品明细
    $items = $request->items;
    foreach($items as $item) {
        InvoiceItem::create([
            'invoice_id' => $invoice->id, // 必须关联发票ID,否则数据脱节
            'item_id' => $item['item_id'],
            'item_name' => $item['item_name'],
            'item_type' => $item['item_type'],
            'item_hsn_sac' => $item['item_hsn_sac'],
            'item_qty' => $item['item_qty'],
            'item_unit' => $item['item_unit'],
            'item_rate' => $item['item_rate'],
            'item_tax_value' => $item['item_tax_value'],
            'item_tax_rate_percentage' => $item['item_tax_rate_percentage'],
            'item_tax_cgst_percentage' => $item['item_tax_cgst_percentage'],
            'item_tax_sgst_percentage' => $item['item_tax_sgst_percentage'],
            'item_tax_igst_percentage' => $item['item_tax_igst_percentage'],
            'item_tax_cess_percentage' => $item['item_tax_cess_percentage'],
            'item_tax_cess' => $item['item_tax_cess'],
            'item_total' => $item['item_total']
        ]);
    }

    return response()->json(['success'=> true, 'message' => '发票及商品明细保存成功']);
}

几个关键细节提醒

  • 前端传的客户姓名字段是customername,你之前控制器里写的$request->inv_customer_name会导致客户姓名存空值,已经帮你修正了。
  • 一定要把invoice_id存入invoice_item表,这是关联发票和商品明细的核心,不然两组数据就完全脱节了。
  • 建议给模型添加关联关系,方便后续查询:
    在Invoice模型中添加:
    public function items() {
        return $this->hasMany(InvoiceItem::class, 'invoice_id');
    }
    
    在InvoiceItem模型中添加:
    public function invoice() {
        return $this->belongsTo(Invoice::class, 'invoice_id');
    }
    
  • 最好添加数据验证,避免无效数据入库,比如在控制器开头加上:
    $request->validate([
        'inv_id' => 'required',
        'customername' => 'required',
        'items' => 'required|array',
        'items.*.item_name' => 'required',
        // 其他必填字段的验证规则可按需添加
    ]);
    

前端代码小优化

可以把AJAX请求改成JSON格式提交,让Laravel处理更规范:

$.ajax({
    url: "{{route('inv.store.post')}}",
    type:'POST',
    contentType: 'application/json',
    data: JSON.stringify(d),
    success: function(response) {
        console.log('保存成功:', response);
        // 这里可以添加成功后的操作,比如清空表单或跳转列表页
    },
    error: function(xhr) {
        console.error('保存失败:', xhr.responseText);
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:03:48