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

Jakub003's avatar

Formatting seconds into hours and minutes with laravel carbon

Problem:

$tracked_time = 994554

In the laravel blade view, I want this to display as 77h 55m

I tried to find a few solutions

{{ Carbon\CarbonInterval::seconds($duration['tracked_time'])->cascade()->forHumans()  ?? '' }}

it displays days and seconds, along with spelling it out.

1 day 7 hours 53 minutes 25 seconds

I also found

gmdate("H:i:s", $seconds);

But that doesn't work when its more than 1 day of seconds.

I tried to use the ->format('H:i:s') on it but it just broke it.

I think the proper way would be format this in the Model with something like

public function timeTrackedForHumans()
{
 return $this->time_tracked->dosometing();

}

So that I could call it like $task->timeTrackedForHumans

Any advice is much appreciated. Is this something that always goes into Model or is it fine to also include it in the blade? Or if anyone knows what I can search for to find like a bunch of examples of how to do these types of formatting functions in the models.

I know this is a big ask and prob a super novice one, but genuinely am lost with this.

0 likes
2 replies
MichalOravec's avatar
Level 75

You can create an accessor in the model. I assume $this->time_tracked is a time in the seconds.

public function getTimeTrackedForHumansAttribute()
{
    return sprintf('%dh %dm', $this->time_tracked / 3600, floor($this->time_tracked / 60) % 60);
}

In blade

{{ $task->time_tracked_for_humans }}

It returns 276h 15m for 994554 seconds.

1 like
JakeCausier's avatar

CarbonInterval allows you to output the total number of a specific unit; for hours you can use totalHours: CarbonInterval::seconds($t)->cascade()->totalHours

You can then parse together multiple outputs to get the string you need:

$interval = CarbonInterval::seconds($t)->cascade();
$output = sprintf('%sh %sm', $interval->totalHours, $interval->toArray()['minutes']);
2 likes

Please or to participate in this conversation.