0

I have a Device.php model with $dates = ['status_updated_at'].

I'd like to bulk update devices with Carbon::now().

I've tried with the following, which seems straightforward:

Device::whereIn('serial_number', $serialNumbers)->update([
    'status_updated_at' => Carbon::now()
]);

However, results in an error:

enter image description here

So I tried saving it as a string instead of the Carbon::now() array:

Device::whereIn('serial_number', $serialNumbers)->update([
    'status_updated_at' => Carbon::now()->toISOString()
]);

However, this does not store it as a date in my DB, it stores it as a string:

enter image description here

Saving as a date does work, and I can achieve this if I save on the model directly, but it results in many unnecessary write operations to the database.

$devices = Device::whereIn('serial_number', $serialNumbers)->get();
foreach ($devices as $device) {
    $device->status_updated_at = Carbon::now();
    $device->save();
}

I feel like I could be missing something obvious but my current thought is that laravel-mongodb package doesn't support this kind of flow...

D'Arcy Rail-Ip
  • 11,505
  • 11
  • 42
  • 67

1 Answers1

0

Looks like the issue is documented here:

https://github.com/jenssegers/laravel-mongodb/issues/2177

My solution was as follows:

$now = (new Device)->fromDateTime(Carbon::now());
Device::whereIn('serial_number', $serialNumbers)->update([
    'status_updated_at' => $now
]);

Since Device.php is extending the Eloquent Model class, that function fromDateTime() is accessible and converts correctly before saving.

D'Arcy Rail-Ip
  • 11,505
  • 11
  • 42
  • 67