Created
October 7, 2025 03:30
-
-
Save kura1420/3aee0eb0b46b0cb992d954dae8426593 to your computer and use it in GitHub Desktop.
Laravel Excel Impot Progress Bar and Output File If Data Cannot Insert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Imports; | |
| use App\Models\CustomerProfile; | |
| use App\Models\Kota; | |
| use Maatwebsite\Excel\Concerns\Importable; | |
| use Maatwebsite\Excel\Concerns\ToModel; | |
| use Maatwebsite\Excel\Concerns\WithHeadingRow; | |
| use Maatwebsite\Excel\Concerns\WithProgressBar; | |
| class CustomerProfileImport implements ToModel, WithHeadingRow, WithProgressBar | |
| { | |
| use Importable; | |
| protected $failedRows = []; | |
| /** | |
| * @param array $row | |
| * | |
| * @return \Illuminate\Database\Eloquent\Model|null | |
| */ | |
| public function model(array $row) | |
| { | |
| $isFail = false; | |
| $exists = CustomerProfile::where('email', $row['email']) | |
| ->orWhere('name', 'ilike', '%' . $row['name'] . '%') | |
| ->orWhere('handphone_1', $row['handphone_1']) | |
| ->exists(); | |
| if (! $exists) { | |
| $city = Kota::where('name', $row['city'])->first(); | |
| if (isset($city) && strlen($row['handphone_1']) <= 15) { | |
| if (filter_var($row['email'], FILTER_VALIDATE_EMAIL) || strpos($row['email'], '@inet.com') !== false) { | |
| return new CustomerProfile([ | |
| // | |
| 'name' => $row['name'], | |
| 'email' => $row['email'], | |
| 'handphone_1' => $row['handphone_1'], | |
| 'address' => $row['address'] ?: 'Alamat tidak diisi', | |
| 'city' => $city ? $city->id : null, | |
| 'status' => 1, | |
| ]); | |
| } else { | |
| $row['message'] = 'Format email tidak valid'; | |
| $this->failedRows[] = $row; | |
| $isFail = true; | |
| } | |
| } else { | |
| $row['message'] = isset($city) ? 'Handphone lebih dari 15 karakter' : 'Kota tidak ditemukan'; | |
| $this->failedRows[] = $row; | |
| $isFail = true; | |
| } | |
| } else { | |
| $row['message'] = 'Data sudah ada'; | |
| $this->failedRows[] = $row; | |
| $isFail = true; | |
| } | |
| if ($isFail) { | |
| $filename = storage_path('app/fails.csv'); | |
| $file = fopen($filename, 'w'); | |
| if ($file === false) { | |
| die('Gagal membuka file untuk ditulisi.'); | |
| } | |
| foreach ($this->failedRows as $row) { | |
| fputcsv($file, $row); | |
| } | |
| fclose($file); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment