php - laravel Excel 导入在列上设置标题

标签 php excel laravel laravel-5 laravel-excel

我有一个来自 laravel excel 的导入函数,它有效,但现在我想在其上添加一个标题,但它不起作用,我的 Excel 工作表中只有 1 列,标题称为 单位类型

<?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 时,它现在给我一个错误,如下所示:

Undefined offset: 0

最佳答案

继续@thmspl的回答,

在行中使用$row['unit_type']

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

而不是$row[0]

关于php - laravel Excel 导入在列上设置标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58316971/

相关文章:

laravel - 为什么 laravel 主要使用 Facades 而不是单例?

php - 在 32 位 Linux 操作系统上使用 PHP 5.2.9 进行错误的 Blowfish 对称 key 加密

php - 将商标符号添加到整个网站的特定短语

excel - 昏暗如字典。编译错误: User-defined type not defined

VBA Excel : return the parent workbook of a range

php - 在独立的非 Laravel 应用程序中照亮验证器

php - Laravel - 将数据传递到电子邮件 View

php - 奇怪的 MySQL 问题

excel - 在 Excel 中比较两个单元格的不同值

laravel - 我如何在 laravel 中测试 back() 方法