Get duration in hours in minutes using Carbon

Laravel offers with Carbon a powerful library to deal with times and date formats of all kinds. I was recently faced with the problem that I record times in minutes, but would like to output them in hours and minutes.

Of course I could build my own function for this with little effort, but I was interested in how to solve the problem with Carbon.

The solution is called CarbonInterval.

The following command creates a CarbonInverval based on minutes:

CarbonInterval::minutes($minutes);

However, this code line now also simply outputs the number of minutes - so we have gained nothing.

To convert the number of minutes into “more meaningful quantities”, i.e. years, months, weeks, days, hours and minutes, Carbon offers the cascade() function.

CarbonInterval::minutes($minutes)->cascade();

However, since I needed the result in hours and minutes format, the larger units like days, weeks, months and years had to disappear.

Fortunately, CarbonInterval can be configured:

CarbonInterval::setCascadeFactors([
    'minute' => [60, 'seconds'],
    'hour' => [60, 'minutes'],
]);

Above code example configures only hours and minutes - larger units are removed. Thus the output of cascade() is now only in the units hours and minutes - goal achieved!

Well, almost, because the configuration is global. All following used CarbonInterval now also output only hours and minutes. To fix this we save the original configuration, set the desired value, generate the output and restore the original configuration:

$cascades = CarbonInterval::getCascadeFactors(); // save initial factors
CarbonInterval::setCascadeFactors([
    'minute' => [60, 'seconds'],
    'hour' => [60, 'minutes'],
]);

$output = CarbonInterval::minutes($minutes)->cascade();
CarbonInterval::setCascadeFactors($cascades); // restore original factors

Now we get the desired result: $minutes will now output in hours and minutes without affecting CarbonInterval globally.