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

Laravel Excel导入验证无返回结果,如何获取验证结果?

问题

在Livewire框架中使用Laravel Excel的Import类验证Excel行数据时,控制器尝试捕获ValidationException获取失败信息,但验证后无任何响应(Excel数据确实存在),无法获取验证结果。

控制器代码:

public function save()
{
    $this->validate();
    
    try {
        $import = new OutputImport();
        $import->import($this->excel);
    } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
        $failures = $e->failures();

        dd($failures);
    }
}

Import类代码:

class OutputImport implements ToCollection, WithStartRow, SkipsEmptyRows
{
    use Importable;

    protected $outputs;
    protected $outputIds;

    public function __construct()
    {
        $this->outputs = Output::where('status',1)->get();
        $this->outputIds = $this->outputs->pluck('id')->toArray();
    }

    public function collection(Collection $rows)
    {
        Validator::make($rows->toArray(), [
            '*.0' => ['required', function(string $attribute, mixed $value, Closure $fail) {
                if (!in_array($value, $this->outputIds))
                    $fail('Periksa dan pastikan kembali ID yang diinput.');     
            }],
            '*.5' => 'required',
            '*.6' => 'required|min:0',
            '*.7' => 'required|min:0',
        ])->validate();
    }

    public function startRow(): int
    {
        return 2;
    }
}
解决方案

问题根源

当前使用Laravel原生Validator进行验证,抛出的是Illuminate\Validation\ValidationException,而非Laravel Excel专属的Maatwebsite\Excel\Validators\ValidationException,导致控制器中的catch块无法捕获异常,自然拿不到验证结果。

修复步骤

  1. 改用Laravel Excel的WithValidation接口
    实现WithValidation接口,通过rules()方法定义验证规则,这是Laravel Excel推荐的验证方式,会自动抛出框架对应的异常:

    修改OutputImport类:

    use Maatwebsite\Excel\Concerns\WithValidation;
    
    class OutputImport implements ToCollection, WithStartRow, SkipsEmptyRows, WithValidation
    {
        use Importable;
    
        protected $outputs;
        protected $outputIds;
    
        public function __construct()
        {
            $this->outputs = Output::where('status',1)->get();
            $this->outputIds = $this->outputs->pluck('id')->toArray();
        }
    
        public function collection(Collection $rows)
        {
            // 此处可保留数据入库等业务逻辑,验证逻辑由rules方法处理
        }
    
        public function rules(): array
        {
            return [
                '0' => ['required', function(string $attribute, mixed $value, Closure $fail) {
                    if (!in_array($value, $this->outputIds))
                        $fail('Periksa dan pastikan kembali ID yang diinput.');     
                }],
                '5' => 'required',
                '6' => 'required|min:0',
                '7' => 'required|min:0',
            ];
        }
    
        public function startRow(): int
        {
            return 2;
        }
    }
    
  2. 验证异常捕获生效
    现在控制器中的catch块可以正确捕获异常,获取失败详情:

    public function save()
    {
        $this->validate();
        
        try {
            $import = new OutputImport();
            $import->import($this->excel);
        } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
            $failures = $e->failures();
            // 可将$failures赋值给Livewire属性,用于前端展示错误
            // $this->importErrors = $failures;
            dd($failures);
        }
    }
    
  3. 定位错误行提示
    每个failure对象包含以下属性,方便定位Excel中的错误位置(注意:row()返回的是Import类处理的行索引,从1开始,对应Excel实际行号为failure->row() + 1,因为startRow设为2):

    • row(): 处理的行索引
    • attribute(): 列索引(0对应A列,以此类推)
    • errors(): 错误信息数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 18:40:19