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

dan3460's avatar

Problem with dates after move to Laravel 10

I have a model that all "time" fields have been created has DateTime on a MySql database. Even when i see that there is time on those fields, when Carbon calls them the time part disappears. See example from tinker:

> $s=Stop::find(854480)
[!] Aliasing 'Stop' to 'App\Models\Stop' for this Tinker session.
= App\Models\Stop {#7571
    id: 854480,
    round_id: 130179,
    planned_sequence: 10,
    appointment: 0,
    planned_arrival: "2023-05-11 15:06:29",
    projected_arrival: "2023-05-11 15:54:30",
    location_id: 39955,
    size1: 14.0,
    time_window_open: "2023-05-11 06:00:00",
    time_window_close: "2023-05-11 14:00:00",
    projected_time_window_missed: -1200,
    stop_reason_id: 1,
    show: 0,
    created_at: "2023-05-11 12:15:23",
    updated_at: "2023-05-11 16:20:52",
  }

> $s->time_window_close
= Illuminate\Support\Carbon @1683763200 {#7561
    date: 2023-05-11 00:00:00.0 UTC (+00:00),
  }

0 likes
6 replies
LaryAI's avatar
Level 58

The issue is that the time_window_close attribute is not being cast to a DateTime object by Laravel. To fix this, you can add the attribute to the $dates property in your Stop model:

class Stop extends Model
{
    protected $dates = [
        'time_window_close',
        // add any other date attributes here
    ];
}

This will tell Laravel to cast the time_window_close attribute to a DateTime object, which should preserve the time component.

dan3460's avatar

I thought protected $dates = [], disappeared from Laravel 10. Is that correct?

1 like
PovilasKorop's avatar

@Snapey no, in Laravel 10 $dates was officially removed, after being deprecated for a few versions, from what I remember

1 like
dan3460's avatar

I think i read the upgrade document 4 times and did not see the date casting. I was in panic because this was the production server, so just for shits and giggles, i tried in the casting:

protected $cast = [
	'time_window_close' => 'datetime'
]

and it worked. Right after that i saw @snapey and @povilaskorop answers. Thanks guys,

1 like

Please or to participate in this conversation.