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

使用maatwebsite/excel导入Excel时Laravel Model未创建数据

问题描述

在Laravel项目中使用maatwebsite/excel包导入Excel用户数据到数据库时,出现异常:

  • 调用导入器后,数据库无任何数据新增
  • 数据表的自增ID持续增长(当前已到86)
    已确认User模型中已将对应属性添加到$fillable中,相关代码如下:

相关代码

App\Imports\UserImport.php

<?php

namespace App\Imports;

use App\Models\Position;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class UsersImport implements ToModel, WithHeadingRow
{

    public function model(array $row)
    {
            User::create([
                'person_code' => $row['prsnly'],
                'username' => $row['prsnly'],
                'national_code' => $row['kd_mly'],
                'password' => $row['kd_mly'],
                'is_active' => User::ACTIVE
            ]);
        }

    }


    public function headingRow(): int
    {
        return 1;
    }


}

routes/web.php

<?php

use App\Imports\UsersImport;
use Illuminate\Support\Facades\Route;
use Maatwebsite\Excel\Facades\Excel;

Route::get('import-chart', function () {
    Excel::import(new UsersImport, public_path('chart.xlsx'));
});
问题原因与解决方法

核心问题

你的UsersImport类实现了ToModel接口,但model方法未返回创建的模型实例。maatwebsite/excel的ToModel逻辑依赖该方法返回的模型对象完成后续持久化操作,虽然你手动调用了User::create(),但框架内部的事务机制(如导入时的隐式事务)会因缺少返回实例触发回滚,导致数据未保存;而自增ID因执行过INSERT操作已被占用,所以出现ID增长但无数据的情况。

修复步骤

修改UsersImport.php中的model方法,返回创建的User实例:

public function model(array $row)
{
    return User::create([
        'person_code' => $row['prsnly'],
        'username' => $row['prsnly'],
        'national_code' => $row['kd_mly'],
        'password' => $row['kd_mly'],
        'is_active' => User::ACTIVE
    ]);
}

或者使用实例化方式返回:

public function model(array $row)
{
    return new User([
        'person_code' => $row['prsnly'],
        'username' => $row['prsnly'],
        'national_code' => $row['kd_mly'],
        'password' => $row['kd_mly'],
        'is_active' => User::ACTIVE
    ]);
}

额外排查点

  • 验证表头匹配:确保Excel文件表头与$row['prsnly']、$row['kd_mly']完全一致(注意大小写、空格),表头不匹配会导致字段值为null,若数据库字段不允许为null会触发错误导致事务回滚。
  • 查看错误日志:检查Laravel的storage/logs/laravel.log文件,里面会记录导入过程中的具体错误,比如字段验证失败、数据库约束冲突等。
  • 检查事务机制:maatwebsite/excel默认开启导入事务,若某一行数据导入失败,整个批次会回滚,但自增ID不会回滚,也会导致ID增长无数据的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:41:12