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.
78 lines
2.4 KiB
78 lines
2.4 KiB
<?php |
|
|
|
namespace App\Imports; |
|
|
|
use App\Models\Customer; |
|
use Illuminate\Support\MessageBag; |
|
use Illuminate\Support\Facades\Auth; |
|
use Illuminate\Support\Facades\Hash; |
|
use Maatwebsite\Excel\Concerns\ToModel; |
|
use Maatwebsite\Excel\Events\AfterImport; |
|
use Maatwebsite\Excel\Concerns\WithHeadingRow; |
|
|
|
class CustomerImport 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 |
|
$existingCustomer = Customer::where('name', $row['name'])->first(); |
|
|
|
if ($existingCustomer) { |
|
// Jika nama warehouse sudah ada, tambahkan pesan kesalahan ke dalam array $errors |
|
$this->errors[] = new MessageBag(['Row ' . $this->rowCount => 'Data Customer sudah ada dalam database.']); |
|
return null; // Abaikan data yang sudah ada |
|
} |
|
|
|
// Increment rowCount setiap kali ada data yang diimpor |
|
$this->rowCount++; |
|
|
|
return new Customer([ |
|
'name' => $row['name'], |
|
'code_customer' => $row['code_customer'], |
|
'lot_no' => $row['lot_no'], |
|
'no_tlp' => $row['no_tlp'], |
|
'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; |
|
} |
|
}
|
|
|