phplaravelphp-carbon

How to Carbon value to add other time field?


In laravel 10 / php 8.2 time I have a time field and in model I have defined cast:

<?php

namespace App\Casts;

use Carbon\Carbon;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class TimeCast implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return  Carbon::parse($value)->format('H:i');
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return $value;
    }
}

and in Item model :

protected function casts(): array
{
    return [
        'time' => TimeCast::class,
    ];
}

I need to Carbon value(with zero time) to add other time field. I do :

$calcDate = Carbon::parse(Carbon::now(\config('app.timezone')))->startOfDay();
$calcDate->addDays(5);

$item = Item::find($id);
$dateTill = $calcDate->addMinutes($item->time);
dd(Carbon::parse($dateTill));
            

But in $dateTill I see only $calcDate value(+5 days without time).

How can I do it ?


Solution

  • You are passing 'H:i' into addMinutes function and that method only accepts integer values.

    One options is in your cast option you will return values into minutes and that you can directly pass into addMinutes.

    public function get(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        $date = Carbon::parse($value);
        return  $date->format('H')*60 + $date->format('i');
    }
    

    In second option you will return time as Carbon instance and in your time addition function you will do a modification.

    public function get(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return Carbon::parse($value);
    }
    
    $dateTill = $calcDate->addHours($item->time->format('H'))->addMInutes($item->time->format('i'))
    

    If you want to add seconds then also you will be able to add that in above. In 1st case, you need to returns seconds and need to addSecods while calculating.