I have 2 features that I'm working on, say Clock in and Clock out. The thing is that when I clock out(updated the Time Clock out and Location Clock out), suddenly there's an extra record as seen on this pic, https://paste.pics/586336ef0bf2517da832678425125655 . Although the data is updated but there's an extra row with an updated info in 'time_checkOut' and 'location_checkOut'. I am wondering what is wrong here ?
I tried inserting and updating the data by injecting time manually by using the code below before and it's working just fine as seen on the screenshot picture above but when I am using Carbon::now() and update the info using this. The data table in the database will double when I clock out.
$date = date('Y-m-d');
$date = $r->date_checkIn;
$time = date('H:i:s');
$time = $r->time_checkIn;
Below are my 2 controllers :
public function userClockIn(Request $r)
{
$result = [];
$result['status'] = false;
$result['message'] = "something error";
$users = User::where('staff_id', $r->staff_id)->select(['staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first();
$mytime = Carbon::now();
$date = $mytime->format('Y-m-d');
$time = $mytime->format('H:i:s');
$users->date_checkIn = $date;
$users->time_checkIn = $time;
$users->location_checkIn = $r->location_checkIn;
$users->save();
// Retrieve current data
$currentData = $users->toArray();
// Store current data into attendace record table
$attendanceRecord = new AttendanceRecord();
$attendanceRecord->fill($currentData);
$attendanceRecord->save();
$result['data'] = $users;
$result['status'] = true;
$result['message'] = "suksess add data";
return response()->json($result);
}
public function userClockOut(Request $r)
{
$result = [];
$result['status'] = false;
$result['message'] = "something error";
$users = User::where('staff_id', $r->staff_id)->select(['staff_id', 'time_checkOut', 'location_checkOut'])->first();
$mytime = Carbon::now();
$date = $mytime->format('Y-m-d');
$time = $mytime->format('H:i:s');
$users->date_checkIn = $date;
$users->time_checkOut = $time;
$users->location_checkOut = $r->location_checkOut;
// Save the updated data to the database
AttendanceRecord::updateOrCreate(
['staff_id' => $users->staff_id, 'date_checkIn' => $date],
$users->toArray()
);
// Retrieve current data
$currentData = $users->toArray();
// Store current data into attendace record table
$attendanceRecord = new AttendanceRecord();
$attendanceRecord->fill($currentData);
$attendanceRecord->save();
$result['data'] = $users;
$result['status'] = true;
$result['message'] = "suksess add data";
return response()->json($result);
}
CodePudding user response:
in function userClockOut:
AttendanceRecord::updateOrCreate(
['staff_id' => $users->staff_id, 'date_checkIn' => $date],
$users->toArray()
);
and
// I suggest you comment these lines
$attendanceRecord = new AttendanceRecord();
$attendanceRecord->fill($currentData);
$attendanceRecord->save();
are duplicate codes.