|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Imports;
|
|
|
|
|
|
|
|
use App\Models\Kondisi_Peti;
|
|
|
|
use Illuminate\Support\Collection;
|
|
|
|
use Illuminate\Support\MessageBag;
|
|
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
use Maatwebsite\Excel\Concerns\ToModel;
|
|
|
|
use Maatwebsite\Excel\Events\AfterImport;
|
|
|
|
use Maatwebsite\Excel\Concerns\ToCollection;
|
|
|
|
use Maatwebsite\Excel\Concerns\WithHeadingRow;
|
|
|
|
|
|
|
|
class KondisiPetiImport implements ToModel, WithHeadingRow
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param array $row
|
|
|
|
*
|
|
|
|
* @return \Illuminate\Database\Eloquent\Model|null
|
|
|
|
*/
|
|
|
|
|
|
|
|
private $rowCount = 0;
|
|
|
|
private $errors;
|
|
|
|
|
|
|
|
public function model(array $row)
|
|
|
|
{
|
|
|
|
// Mendapatkan informasi pengguna yang sedang login
|
|
|
|
$user = Auth::user();
|
|
|
|
|
|
|
|
// Cek apakah nama warehouse sudah ada dalam database
|
|
|
|
$existingKondisiPeti = Kondisi_Peti::where('nama_kondisi', $row['nama_kondisi'])->first();
|
|
|
|
|
|
|
|
if ($existingKondisiPeti) {
|
|
|
|
// Jika nama warehouse sudah ada, tambahkan pesan kesalahan ke dalam array $errors
|
|
|
|
$this->errors[] = new MessageBag(['Row ' . $this->rowCount => 'Data Kondisi Peti sudah ada dalam database.']);
|
|
|
|
return null; // Abaikan data yang sudah ada
|
|
|
|
}
|
|
|
|
|
|
|
|
// Increment rowCount setiap kali ada data yang diimpor
|
|
|
|
$this->rowCount++;
|
|
|
|
|
|
|
|
return new Kondisi_Peti([
|
|
|
|
'nama_kondisi' => $row['nama_kondisi'],
|
|
|
|
'deskripsi_kondisi' => $row['deskripsi_kondisi'],
|
|
|
|
'created_by' => $user->fullname,
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function registerEvents(): array
|
|
|
|
{
|
|
|
|
return [
|
|
|
|
AfterImport::class => function (AfterImport $event) {
|
|
|
|
// Setelah import selesai, kita bisa mengakses semua data yang diimpor
|
|
|
|
$importedData = $event->getReader()->getDelegate()->getActiveSheet()->toArray();
|
|
|
|
|
|
|
|
// Lakukan pemeriksaan apakah ada data yang bernilai null dan hapus dari hasil import
|
|
|
|
$filteredData = array_filter($importedData, function ($row) {
|
|
|
|
return $row[0] !== null; // Jika nilai kolom pertama tidak null, pertahankan baris tersebut
|
|
|
|
});
|
|
|
|
|
|
|
|
// Update hasil import dengan data yang telah difilter
|
|
|
|
$event->getReader()->getDelegate()->getActiveSheet()->fromArray($filteredData);
|
|
|
|
},
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getErrors()
|
|
|
|
{
|
|
|
|
return $this->errors;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function getRowCount()
|
|
|
|
{
|
|
|
|
return $this->rowCount;
|
|
|
|
}
|
|
|
|
}
|