mercredi 9 octobre 2019

laravel Excel Import set header on column

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

Undefined offset: 0



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire