0

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

reans
  • 352
  • 1
  • 5
  • 16
  • 4
    Can you post what you've attempted please? – War10ck Jan 25 '23 at 16:27
  • @war10ck This is the insert statement I am executing: `Item::insert(['date' => Carbon\Carbon::parse('2023-01-24T02:02:02.222222Z')]);`. I can get this statement to save with timestamp precision by formatting to string. I'm looking for a global setting though. – reans Jan 25 '23 at 16:42
  • @Arleigh Hix MySQL version is 5.7.37. I'm able to get millisecond precision in MySQL if I manually set the string before insert, but not through Carbon. – reans Jan 25 '23 at 16:44
  • Laravel version? – Arleigh Hix Jan 25 '23 at 16:46
  • @Arleigh Hix Laravel version is 8.83.23 – reans Jan 25 '23 at 16:46
  • Have you set the `$dateFormat` property on your model? – Arleigh Hix Jan 25 '23 at 16:48
  • @ArleighHix yes it is set but should not matter here because we are bypassing the model using bulk insert. – reans Jan 25 '23 at 17:00
  • The question is very unclear, specifically what you've tried and what happens. Can you edit and show all the various different approaches you've tried, and the results? Searching for "*laravel milliseconds*" turns up some answers here already, have you reviewed those? https://stackoverflow.com/q/31227069/6089612, https://stackoverflow.com/q/54423856/6089612, ... – Don't Panic Jan 26 '23 at 10:30
  • @Don'tPanic The question states the input, output and what is expected. These links refer to PHP 7.2 which I am not using (Laravel 8 minimum version is 7.3) and also updating through the model, as stated in the question - I am doing a bulk insert which does not use the Laravel model. – reans Jan 26 '23 at 10:58

0 Answers0