MIF_E31210141/app/Imports/SiswaImport.php

80 lines
2.4 KiB
PHP

<?php
namespace App\Imports;
use App\Models\Siswa;
use App\Models\User;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Str;
use Carbon\Carbon;
class SiswaImport implements ToCollection
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function collection(Collection $rows)
{
$user = [];
$siswa = [];
foreach ($rows as $row) {
$checkUser = User::where('name', $row[0])->count();
if ($checkUser == 0) {
$username = strtolower(explode(' ', $row[0])[0]);
$email = $username . rand(111, 999) . "@smapa.com";
$user[] = [
'name' => $row[0],
'username' => $username . rand(111, 999),
'email' => $email,
'password' => bcrypt('default123'),
'level' => 4,
'status' => 1,
];
}
}
// Insert all users
User::insert($user);
// Retrieve the newly inserted users to get their IDs
foreach ($user as $userData) {
$insertedUser = User::where('email', $userData['email'])->first();
$row = $rows->firstWhere(0, $userData['name']); // Assuming the name is unique
$checkSiswa = Siswa::where('nis', $row[1])->count();
if ($checkSiswa == 0) {
$siswa[] = [
'id' => Str::uuid(),
'user_id' => $insertedUser->id,
'nis' => $row[1],
'agama' => $row[2],
'agama_ayah' => $row[3],
'kota_siswa' => $row[4],
'alamat' => $row[5],
'nama_ibu' => $row[6],
'telepon' => $row[7],
'pekerjaan_ibu' => $row[8],
'pekerjaan_ayah' => $row[9],
'tempat_lahir' => $row[10],
'nama_ayah' => $row[11],
'tanggal_lahir' => date('Y-m-d', strtotime($row[12])),
'telepon_ortu' => $row[13],
'agama_ibu' => $row[14],
];
}
}
// Insert all siswa
if (!empty($siswa)) {
Siswa::insert($siswa);
}
return true;
}
}