3

I have an import function from laravel excel, it worked but now I want to add a header on it and its not working, There's only 1 column in my excel sheet and the header is called 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;
    }
}

when I try using the method WithHeadingRow it now gives me an error as:

Undefined offset: 0

M.Izzat
  • 1,086
  • 4
  • 22
  • 50

3 Answers3

4

Continuing with @thmspl's answer,

Use $row['unit_type'] in the line

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

instead of $row[0].

3

headingRow method is only required when your Heading is at a row other than 1st Row. In your case since the Heading is first row you can remove the following method.

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

ascsoftw
  • 3,466
  • 2
  • 15
  • 23
2

According to the Docs https://docs.laravel-excel.com/3.1/imports/heading-row.html you don't have to add the headingRow() function if your header is on the first line.

So try to remove the headingRow() function and execute it again.

thmspl
  • 2,437
  • 3
  • 22
  • 48