how to skip the row about importing excel laravel with the Maatwebsite/Laravel-Excel

Viewed 1691

I have a problem to skip the row about importing excel laravel with the Maatwebsite / Laravel-Excel package. I tried many ways from the internet but it still didn't work.

this is my controller code

if ($request->hasFile('file')) {
        $import = new HsatuImport();
        $file = $request->file('file'); //GET FILE
        // config(['excel.import.startRow' => 2]);
        Excel::import($import, $file)->limit(false, 2); //IMPORT FILE
        return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Berhasil '.$import->getRowCount().' Data');
    } else {
        return redirect()->route('admin.hsatus.upload')->withFlashSuccess('Upload Gagal');
    }

and this is my import code

<?php

namespace App\Imports;

use App\Models\Hsatu;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\ToModel;

class HsatuImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    private $rows = 0;
    public function model(array $row)
    {
        ++$this->rows;
        return new Hsatu([
            'region' => @$row[0],
            'nomor_faktur' => @$row[1],
            'nomor_rangka' => @$row[2],
            'kode_mesin' => @$row[3]
        ]);
    }

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

    public function getRowCount(): int
    {
        return $this->rows;
    }
}

1 Answers

I had the problem with skipping when there's already existing Eloquent model. So below my code:

public function model(array $row)
    {
        $name = $row['name'];
        if (!Category::where('name', $name)->exists())
            return new Category([
                'name' => $name
            ]);
    }

I'm returning Model instance only if given statement is true.

Related