I want to calculate late entry from difference between check_in time and opening_time from Settings table and store the time value in attendance table. Time formate : 10:15:00
. The check_in and check_out time will come from request.
Example:
open = 10:15:00
end = 18:00:00
check_in = 10:18:00
check_out = 17:50:00
late = open - check_in = 00:03:00
early = end - check_out = 00:10::
Please see below code
Settings Table
id | opening_time | ending_time |
---|---|---|
1 | 10:15:00 | 18:00:00 |
attendance table
id | late | early |
---|---|---|
1 | 00:20:00 | 00:05:00 |
Controller:
public function AttendanceCSVStore(Request $request)
{
$settings = Setting::where('id', 1)->get();
$open = time($settings->opening_time);
$end = time($settings->ending_time);
for ($x = 1; $x <= $request->number; $x ) {
$attendances = new Attendance;
$attendances->check_in = $request->$x[4];
$attendances->check_out = $request->$x[5];
$csv_check_in = time($request->$x[4]);
$csv_check_out = time($request->$x[5]);
if( $csv_check_in > $open){
$late_count = $csv_check_in - $open;
$attendances->late = $late_count;
}
if( $csv_check_out < $end){
$early_count = $csv_check_out - $end;
$attendances->early = $early_count;
}
$attendances->save();
}
return redirect()->route('admin.attendance.manage')->with('message', 'Imported Successfully!');
}
This shows error Property [opening_time] does not exist on this collection instance.
And also this doesn't calculate and insert time in late, early column.
Can you please help me to solve this?
CodePudding user response:
You get a collection, not a single record.
If you need a single record instead of a collection, you can get it by this way
$id = 1;
$settings = Setting::find($id);
echo $settings->opening_time;
or
$id = 1;
$settings = Setting::where('id', $id)->firstOrFail();
echo $settings->opening_time;
If you need a collection and iterate on it, you can do it like that (But I don't think this is what you are after)
$settings = Setting::where('id', 1)->get();
foreach ($settings as $setting) {
echo $setting->opening_time;
}
UPDATE
Time difference example
public function index()
{
$startTime = Carbon::parse('2020-02-11 04:04:26');
$endTime = Carbon::parse('2020-02-11 04:36:56');
$totalDuration = $startTime->diff($endTime)->format('%H:%I:%S');
dd($totalDuration);
}
Output: "00:32:30"
I think this is the format you are after