I have a timestamp(6)
column in my database called date
. When I use the Model::insert()
method to insert to the database - bypassing Eloquent and using Laravel QueryBuilder, the timestamp precision is lost.
Eg. if I pass '2023-01-24T02:02:02.222222Z' to the date
column:
Item::insert(['date' => Carbon\Carbon::parse('2023-01-24T02:02:02.222222Z')]);
I will have a timestamp which is saved as '2023-01-24T02:02:02.000000Z' in the database. The timestamp milliseconds is all zeros.
I can apply a format to convert the Carbon object to a string before saving. This works - but I am looking to apply this to every instance in my project so it is not ideal.
The __toString
Carbon method formats a datetime to seconds precision. If I can change this default then this can be applied globally, but the only method I can find to do this is deprecated: setToStringFormat
.
If I was globally able to set the DEFAULT_TO_STRING_FORMAT = 'Y-m-d H:i:s';
const in CarbonInterface.php
to include milliseconds like DEFAULT_TO_STRING_FORMAT = 'Y-m-d H:i:s.u';
this might work. I'd like Carbon to always save milliseconds for all datetimes in my project.
How can I achieve this?
MySQL version is 5.7.37
Laravel version is 8.83.23
PHP version is 8.1