CasperSecurity
<?php
namespace App\Imports;
use App\Models\EmployeeAttendance;
use App\Models\EmployeeRegistration;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Carbon\Carbon;
class AttendanceImport implements ToModel,WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
//dd($rows['date']);
// foreach ($rows as $row) {
//dd($row);
$empid=$row['employee_id'];
// $empid="NEX".$row['employee_id'];
$empreginfo=EmployeeRegistration::where('employee_id',$empid)->latest()->first();
$starttime=$lateallowed=$assignworkinghours="";
$empattendance=[];
if ($empreginfo) {
// Loop through each column in the row to capture attendance for each day
foreach ($row as $key => $value) {
// Check if the key is a date (format YYYY-MM-DD) and skip non-date fields
if (preg_match('/\d{4}-\d{2}-\d{2}/', $key)) {
// Parse the date
$attendanceDate = Carbon::parse($key)->format('Y-m-d');
// Check for an existing attendance record for this date and employee to avoid duplicates
$existingAttendance = EmployeeAttendance::where('employee_id', $empreginfo->id)
->whereDate('attendance_date', $attendanceDate)
->first();
if ($existingAttendance) {
// Update the existing record with the "Yes" or "No" status
$existingAttendance->update([
'status' => strtolower($value) === 'yes' ? 1 : 0,
]);
} else {
// Create a new record for this employee and date with "Yes" or "No" status
EmployeeAttendance::create([
'employee_id' => $empreginfo->id,
'attendance_id' => $empid,
'attendance_date' => $attendanceDate,
'status' => strtolower($value) === 'yes' ? 1 : 0,
]);
}
}
}
}
}
}