1

I am trying to build a time-tracker, in where it has a 'time_tracks' table. An employee can track the time many times in a single day. Now I want to sum the 'total_time' where 'track_date' are same. Would someone help me to find out the expected results, please! Here is my 'trackForToday' function is bellow-

public function trackForToday()
{
    $user_id = Auth::user()->id;

    $last_date = TimeTrack::where('employee_id', $user_id)->select('track_date')->orderBy('track_date', 'DESC')->first();
    $last_work_time = TimeTrack::where('employee_id', $user_id)->where('track_date', $last_date->track_date)->get();

    return view('employee.time-tracker.today');
}

And this is my 'time_tracks' table- enter image description here

Rashed Hasan
  • 3,721
  • 11
  • 40
  • 82

1 Answers1

2

Use sum() collection method and as you are using time type as column type(seems) , you may need to convert it to seconds before summing it.

$total_time = TimeTrack::where('employee_id', $user_id)->where('track_date', $last_date->track_date)->sum(DB::raw("TIME_TO_SEC(total_time)"));

To get data of a specific track date-

$track_date = '2018-03-01';
$total_time = TimeTrack::where('track_date', $track_date)->sum(DB::raw("TIME_TO_SEC(total_time)"));

Last to show it, you need to convert back to time format, see this link for that.

The sum method returns the sum of all items in the collection. If the collection contains nested arrays or objects, you should pass a key to use for determining which values to sum.

Sohel0415
  • 9,523
  • 21
  • 30