laravel Excel 列上的导入集 header

laravel Excel Import set header on column

我有一个来自 laravel excel 的导入函数,它可以工作,但现在我想在上面添加一个 header 但它不起作用,我的 excel 中只有 1 列 sheet 而 header 被称为 Unit Type.

<?php

namespace App\Imports;

use App\UnitType;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class UnitTypesImport implements ToCollection, WithHeadingRow
{
    protected $user_id;
    protected $proj_id;

    public function __construct($user_id, $proj_id)
    {
        $this->user_id = $user_id;
        $this->proj_id = $proj_id;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row)
        {   
            $unit_types_count = UnitType::where('name', $row[0])->where('project_id', $this->proj_id)->count();
            if ($unit_types_count == 0){
                UnitType::create([
                    'name'       => $row['unit_type'],
                    'created_by' => $this->user_id,
                    'project_id' => $this->proj_id,
                ]);
            } 
        } 
    }

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

当我尝试使用方法 WithHeadingRow 时,它现在给我一个 error 作为:

Undefined offset: 0

headingRow 方法仅在您的标题位于第一行以外的一行时才需要。在您的情况下,由于标题是第一行,您可以删除以下方法。

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

根据文档 https://docs.laravel-excel.com/3.1/imports/heading-row.html 如果您的 header 在第一行,您不必添加 headingRow() 函数。

所以尝试去掉headingRow()函数再执行

继续@thmspl 的回答,

在行

中使用 $row['unit_type']

$unit_types_count = UnitType::where('name', $row[0])->where('project_id', $this->proj_id)->count();

而不是 $row[0]