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

Laravel Excel验证:日志与前端显示的剂量错误信息不一致

Laravel Excel验证错误:日志与前端数值不一致问题

问题分析

服务器端日志显示剂量数值正确(25),但前端展示为5,同时错误信息中的疫苗名称格式异常(日志显示.FMD.),核心问题集中在以下几点:

  • 错误信息字符串拼接存在格式漏洞,导致符号异常
  • 错误信息在传递或前端渲染阶段被错误修改
  • 行号关联逻辑可能存在索引与实际行号不匹配的情况

修复步骤

1. 修正错误信息字符串格式

统一变量插值方式,移除多余符号,避免解析异常:

$message = "The DOSE set for '{$inventory->name}' is '{$totalDoses}' — any dose given above '{$totalDoses}' should not be added.";
  • 去掉$inventory->name后的多余点,避免出现FMD.格式问题
  • 全程使用{$variable}插值,确保变量正确解析

2. 绑定正确的Excel行号

Laravel Excel数据行索引从0开始(表头占1行),需转换为实际表格行号后再添加错误:

// 转换为Excel实际行号(表头为行1,数据行从行2开始)
$actualRowNumber = $key + 2;
$validator->errors()->add('row-' . $actualRowNumber, $message);

这样前端能精准定位错误行。

3. 排查错误传递与渲染逻辑

  • 在添加错误后,立即打印验证错误集合,确认服务器端存储的信息是否正确:
    Log::info('Validator errors:', $validator->errors()->all());
    
  • 检查前端代码,确保直接读取服务器返回的错误内容,无额外字符串替换或错误映射逻辑。

4. 确保Inventory数据一致性

处理疫苗名称空格问题,强制转换数值类型,避免查询或数据类型异常:

$vaccine = trim($row['vaccine']); // 去除疫苗名称前后空格
$inventory = Inventory::where('name', $vaccine)
    ->where('inventory_type_id', 15)
    ->first();

if ($inventory) {
    $totalDoses = (int)$inventory->dose_numbers; // 强制转为整数,确保数值准确
    Log::info('Confirmed inventory dose numbers: ' . $totalDoses);
    // 后续验证逻辑
}

完整修正代码示例

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        $data = $validator->getData();

        foreach ($data as $key => $row) {
            $vaccine = trim($row['vaccine']);
            Log::info('Processing vaccine: ' . $vaccine);
            
            $inventory = Inventory::where('name', $vaccine)
                ->where('inventory_type_id', 15)
                ->first();

            if (!$inventory) {
                $actualRowNumber = $key + 2;
                $errorMsg = "The vaccine '{$vaccine}' does not exist.";
                Log::error($errorMsg);
                $validator->errors()->add('row-' . $actualRowNumber, $errorMsg);
            } else if (isset($row['given_doses']) && (int)$row['given_doses'] > (int)$inventory->dose_numbers) {
                $totalDoses = (int)$inventory->dose_numbers;
                $actualRowNumber = $key + 2;
                $message = "The DOSE set for '{$inventory->name}' is '{$totalDoses}' — any dose given above '{$totalDoses}' should not be added.";
                
                Log::info("Dose numbers for '{$inventory->name}': {$totalDoses}");
                Log::info("Processing row {$actualRowNumber}: Vaccine '{$vaccine}', Given Doses: '{$row['given_doses']}', Inventory Dose Numbers: '{$totalDoses}'");
                Log::error($message);
                
                $validator->errors()->add('row-' . $actualRowNumber, $message);
            }
        }
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:58:10