Adding the mutator does indeed avoid the error – but why doesn't the date cast do this? Does everyone have to do this for every date property? I feel like I must be missing something!
Date cast format not being applied
A model (in Laravel 8.49) contains:
protected $dateFormat = 'Y-m-d';
protected $casts = [
'service_start' => 'date:Y-m-d',
];
and the service_start field is defined as a date in the MySQL DB.
Yet in a controller that receives a service_start param containing 2021-06-29 00:00:00 (the serialization of Carbon::today()), the format makes it all the way through to the model during a create, resulting in an error:
ERROR: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '2021-06-29T00:00:00.000000Z' for column 'service_start' at row 1
Give that this datetime format in the query is clearly different to what was in the request, something is processing it to give it that format.
I see lots of references to the $dates property, but that no longer seems to be documented so I gather it's obsolete (I assume replaced by $casts) – but I don't know for sure.
I've also seen mention of using a mutator like this:
public function setServiceStartAttribute($date): void
{
$this->attributes['service_start'] = Carbon::parse($date);
}
Why would that be necessary? Isn't this what the cast does anyway?
Why isn't this date being cast according to the format it's been given?
Please or to participate in this conversation.