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

rafaeladi's avatar

Using carbon to convert second to time

So i want to convert my duration data from database to be viewed on my view page. I tried made some function on my controller that should convert it.

    public function humanTime()
    {
        $seconds = DB::table('test_executions as e')
                        ->select('e.duration');
        $time = CarbonInterval::seconds($seconds)->cascade()->forHumans();
        dd($time);
	}

And on my view page i want to show it and currently i have this.

    @foreach ($test_data['details'] as $value)
    <tr>      
    <th scope="row" class='col-auto align-middle'>{{$value->name}}</td>
    <td scope="row" class='col-3 align-middle'>{{$value->description}}</td>
    <td scope="row" class='col-auto align-middle'>{{humanTime($value->duration)}}</td>
	</tr>
	@endforeach

But currently i only get an error that state:

'Call to undefined function humanTime()' and when i tried to test the function also shows that the collection cannot be converted to int.

0 likes
5 replies
MichalOravec's avatar
@foreach ($test_data['details'] as $value)
    <tr>      
        <th scope="row" class="col-auto align-middle">{{$value->name}}</td>
        <td scope="row" class="col-3 align-middle">{{$value->description}}</td>
        <td scope="row" class="col-auto align-middle">{{ CarbonInterval::seconds($value->duration)->cascade()->forHumans() }}</td>
    </tr>
@endforeach

Or use accessor with Eloquent

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TestExecution extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFormattedDurationAttribute()
    {
        return CarbonInterval::seconds($this->duration)->cascade()->forHumans()
    }
}

Docs: https://laravel.com/docs/8.x/eloquent and https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

rafaeladi's avatar

i tried the first one but it always said that the CarbonInterval is not found. I already put it on my controller but idk how to declare it on blade.

rafaeladi's avatar

@michaloravec I already add it on my config file like this

        'Carbon' => Illuminate\Support\Carbon::class,
        'CarbonInterval' => Illuminate\Support\CarbonInterval::class,

But it still give me an error

Class "Illuminate\Support\CarbonInterval" not found
MichalOravec's avatar
Level 75

Namespace is Carbon\CarbonInterval

<td scope="row" class="col-auto align-middle">
    {{ Carbon\CarbonInterval::seconds($value->duration)->cascade()->forHumans() }}
</td>

In config it has to be as

'CarbonInterval' => Carbon\CarbonInterval::class,
1 like

Please or to participate in this conversation.