如何在 maatwebsite-excel 3.1 中跳过空白行以在 Laravel 上进行模型方式导入

joe*_*ion 4 laravel maatwebsite-excel

我正在使用 laravel 项目maatwebsite-exvel 3.1从文件上传方法导入 excel 文件。这是我的StudentsImport课。

public function model(array $row)
{
    return new Student([
        'school_uuid' => Auth::user()->school_uuid,
        'cardid'     => $row[0],
        'prefix'    => $row[1], 
        'name'    => $row[2], 
        'lastname'    => $row[3], 
        'dob'    => $row[4], 
        'address'    => $row[5], 
        'phone'    => $row[6], 
    ]);
}
Run Code Online (Sandbox Code Playgroud)

下面是控制器。

 Excel::import(new StudentsImport,  $request->file('file'));
Run Code Online (Sandbox Code Playgroud)

代码工作正常。我可以将 excel 的数据导入数据库,但也导入了空白行。我想过滤/验证以在放入数据库之前跳过这些空白。对此的任何建议或指导将不胜感激,谢谢

aty*_*mic 5

根据包文档,支持使用 Laravel 的验证来防止插入无效行。

要使用它,请WithValidation在导入器类上实现接口并添加一个rules()方法,该方法返回应用于确保行有效的验证规则。

public function rules(): array
{
    return [
        '0' => 'required|string',
        '1' => 'required|string',
        '2' => 'required|numeric',
        // so on
    ];
}
Run Code Online (Sandbox Code Playgroud)


Had*_*azi 4

我使用了一种对我的情况有帮助的解决方法。验证通过所有行上的可为空来扩展以避免错误,然后在该方法中,我添加了以下代码并且它有效

public function model(array $row) 
{
  if(!array_filter($row)) {
     return null;
  } 

  // your code will be here
   return new Student([
        'school_uuid' => Auth::user()->school_uuid,
        'cardid'     => $row[0],
        'prefix'    => $row[1], 
        'name'    => $row[2], 
        'lastname'    => $row[3], 
        'dob'    => $row[4], 
        'address'    => $row[5], 
        'phone'    => $row[6], 
    ]);
Run Code Online (Sandbox Code Playgroud)

并在此时跳过这些行。对此不太满意,因为我无法返回有用的错误消息,但因为我没有找到让代码运行的最佳方法的解决方案。我从这里找到了这个。 https://github.com/SpartnerNL/Laravel-Excel/issues/1861#issuecomment-520753182