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

Laravel表单下拉框提交报错:brand字段不能为空问题求助

问题分析与解决

核心问题

提交时出现SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'brand' cannot be null,原因是控制器未获取表单下拉框选中的brand值,反而从Supplier模型中读取brand,但该值为空。同时视图下拉框存在两处细节问题:默认选项未设置空值、所有选项value重复。


修复步骤

1. 修正视图下拉框

  • 给默认选项设置value="",配合required属性实现前端验证拦截
  • 为每个选项设置唯一的有效值

修改后的视图代码:

<div class="form-group row">
    <label style="font-size: 16px;" for="id" class="col-sm-2">Item Brand </label>
    <label for="supp_name" class="col-sm-1">:</label>
    <div class="col-sm-7">
        <select name="brand" class="form-control js-example-basic-single" required>
            <option value="">Please select item brand</option>  
            <option value="machine1"> Item Brand 1 </option>  
            <option value="machine2"> Item Brand 2 </option>  
            <option value="machine3"> Tem Brand 3 </option>  
        </select>
    </div>  
</div>

2. 修正控制器逻辑,获取表单提交的brand值

将原本从Supplier模型取brand的逻辑,改为直接获取表单提交的$r->brand,同时添加请求验证提前拦截无效参数:

修改后的控制器代码:

public function createsupplierdetails()
{
    return view ('frontend.praiBarcode.getweight');
}

public function supplierdetails(Request $r)
{
    // 验证请求参数,确保PO存在且已选择brand
    $r->validate([
        'PO' => 'required|exists:suppliers,PO',
        'brand' => 'required',
    ]);

    $details = new SupplierDetail;
    $getuserPO = Supplier::where('PO',$r->PO)->first();

    // 赋值表单选中的brand值
    $details->brand = $r->brand;
    $details->container_no = $getuserPO->container_no;
    $details->date_received = $getuserPO->date_received;
    $details->gross_weight = $getuserPO->gross_weight;
    $details->tare_weight = $getuserPO->tare_weight;
    $details->net_weight = $getuserPO->net_weight;
    $details->save();

    return view ('frontend.praiBarcode.viewsupplierdetails')
        ->with('details',$details);
}

额外注意

确保SupplierDetail模型中已将brand加入$fillable数组,否则无法正常赋值保存:

// SupplierDetail模型代码
protected $fillable = ['brand', 'container_no', 'date_received', 'gross_weight', 'tare_weight', 'net_weight'];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:50:41