Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Friedrich's avatar

Compute the total TIME IN and TIME OUT of HOURS

My code only compute the total hours of last array of data and also didn't compute the null value

 $day=Tms::where('users_id',$request->user)->whereBetween('day', [$request->first, $request->last])->get();
            $users=Tms::where('users_id', $request->user)->take(1)->get();
           
            foreach($day as $hour){
                $timeIn=Carbon::createFromFormat('g:i A', $hour->time_in);
                $timeOut=Carbon::createFromFormat('g:i A', $hour->time_out);
                $total_minutes=$timeIn->diffInMinutes($timeOut);
                //  dd($hour->time_in);
            }
            $total=$total_minutes/60;
return view('home.admin.tms.calculated_hours')->with(['day'=>$day,'totalHR'=>$total, 'user'=>$users]);

My problem is how to fix this that compute all the time in and time out total hours of WhereBetween date

0 likes
2 replies
Friedrich's avatar

I want to compute all the users time in and time out then if the time in and time out is null i skip that in computation to avoid error and sum all total of hours

jaseofspades88's avatar

I would suggest an accessor on your TMS model, which computes the difference between time_in and time_out. Then you can append this value to your model.

public getDifferenceAttribute()
{
    return $this->time_in->diffInMinutes($this->time_out);
}

This assumes you've cast your time_in and time_out to Carbon instances on your model and will never be null. You will be able to use this example to get the difference by simply doing the following:

$tms = Tms::query()
    ->where('users_id', $request->user)
    ->whereBetween('day', [$request->first, $request->last])
    ->first();

$tms->difference; //should give you the computed difference between the two fields

Please or to participate in this conversation.