MIF_E31221225/app/Imports/GuruImport.php

56 lines
2.0 KiB
PHP

<?php
namespace App\Imports;
use App\Models\Guru;
use App\Models\User;
use App\Models\TahunAjaran; // Add this line
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class GuruImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
// Check if email already exists in users
if (User::where('email', $row['email'])->exists()) {
// If it exists, skip importing this row or update as needed
return null;
}
// Find the TahunAjaran based on a unique identifier from your Excel file
// For example, if you have 'tahun_ajaran_nama' or 'tahun_ajaran_id' in your Excel
$tahunAjaran = TahunAjaran::where('tahun', $row['tahun_ajaran'])->first(); // Assuming 'tahun_ajaran' column in your Excel
// If the academic year doesn't exist, you might want to:
// 1. Skip this row (return null)
// 2. Create a new TahunAjaran (less common for import)
// 3. Log an error
if (!$tahunAjaran) {
// Option 1: Skip if Tahun Ajaran is not found
return null;
// Or throw an exception if you want strict validation
// throw new \Exception("Tahun Ajaran '{$row['tahun_ajaran']}' not found.");
}
// Create new user
$user = User::create([
'name' => $row['nama'],
'email' => $row['email'],
'password' => Hash::make($row['password'] ?? 'passworddefault'),
'role' => 'guru',
'is_active' => true,
]);
// Create guru data with user_id and tahun_ajaran_id
return new Guru([
'user_id' => $user->id,
'nip' => $row['nip'],
'nama' => $row['nama'],
'jenis_kelamin' => $row['jenis_kelamin'],
'jabatan' => $row['jabatan'],
'tahun_ajaran_id' => $tahunAjaran->id, // Assign the found tahun_ajaran_id
]);
}
}