You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.9 KiB
87 lines
2.9 KiB
<?php |
|
|
|
namespace App\Imports; |
|
|
|
use App\Models\m_warehouse; |
|
use Illuminate\Validation\Rule; |
|
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 WarehouseImport implements ToModel, WithHeadingRow |
|
{ |
|
/** |
|
* @param array $row |
|
* |
|
* @return \Illuminate\Database\Eloquent\Model|null |
|
*/ |
|
private $rowCount = 0; |
|
private $errors; |
|
|
|
public function model(array $row) |
|
{ |
|
$requiredColumns = ['name', 'description', 'address']; |
|
|
|
foreach ($requiredColumns as $column) { |
|
if (!array_key_exists($column, $row) || empty($row[$column])) { |
|
$this->errors[] = 'Kolom ' . $column . ' pada baris ' . $this->rowCount . ' tidak boleh kosong.'; |
|
return null; // Abaikan data dengan kolom yang tidak sesuai |
|
} |
|
} |
|
|
|
// Mendapatkan informasi pengguna yang sedang login |
|
$user = Auth::user(); |
|
|
|
// Cek apakah nama warehouse sudah ada dalam database |
|
$existingWarehouse = m_warehouse::where('name', $row['name'])->first(); |
|
|
|
if ($existingWarehouse) { |
|
// Jika nama warehouse sudah ada, tambahkan pesan kesalahan ke dalam array $errors |
|
$this->errors[] = new MessageBag(['Row ' . $this->rowCount => 'Data warehouse sudah ada dalam database.']); |
|
return null; // Abaikan data yang sudah ada |
|
} |
|
|
|
// Increment rowCount setiap kali ada data yang diimpor |
|
$this->rowCount++; |
|
|
|
// Buat model baru jika nama warehouse belum ada |
|
return new m_warehouse([ |
|
'name' => $row['name'], |
|
'description' => $row['description'], |
|
'address' => $row['address'], |
|
'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; |
|
} |
|
}
|
|
|