Omar Alsayed Ahmad
Omar Alsayed Ahmad

Reputation: 11

How to calculate total time in laravel

I have Project about timesheet, i have tasks table and timers table, each task has many timers and timers belong to task.

I calculated the time between start_at and end_at timer in getTotalAttribute ,and i got the difference between them in minutes.

Timer Model

class TsTimer extends Model
{
    use HasFactory;

    public $appends = ['total'];

    public $casts = [
        'start' => 'datetime',
        'end' => 'datetime',
    ];

    public function task(){
        return $this->belongsTo(TsTask::class);
    }

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function getTotalAttribute(){
        // calclute the difference between two time start and end in mints.
        if($this->end){
            return $this->start->diffInMinutes($this->end);
        }     
    return 0;
    }

Task Model

class TsTask extends Model
{
    use HasFactory;

    public $appends = ['total', 'timer_total'];

    public function project(){
        return $this->belongsTo(TsProject::class);
    }

    public function timers(){
        return $this->hasMany(TsTimer::class,'task_id');
    }

    public function getTotalAttribute(){
        $format=$this->timers->sum('total');
        return date('i:s',$format);
    }

And now i need to calculate total time for these timers, like for example first timer (4hours - 10 min), second timer (1 hour), the total will be 5:10.

So i need to calculate this total , any help or suggestion please, i have no idea how to calculate it.

Thanks in advance

Here photo about app:

App overview Image

Upvotes: 1

Views: 1778

Answers (1)

Bhargav Rangani
Bhargav Rangani

Reputation: 355

try this into your task model

public function getTotalAttribute(){

  $totalminutes = 0;
    foreach($this->timers->get() as $timer)
        $startTime = Carbon::parse($timer->start_time);
        $endTime = Carbon::parse($timer->end_time);
        $duration = $endTime->diffInMinutes($startTime);
        $totalminutes += $duration;
    }

    return date('H:i', mktime(0, $totalminutes));
}

Upvotes: 2

Related Questions