Skip to content

Commit b7f0796

Browse files
committed
fix: toRawArray() should convert DateTime objects to strings
Fixes #8302 When a date field listed in $dates is set on an Entity, __set() converts it to a Time object via mutateDate(). However, toRawArray() returned $this->attributes directly without converting Time/DateTime objects back to strings. This caused toRawArray() to return Time objects for date fields that were manually set, e.g.: $user->updated_at = '2023-12-12 12:12:12'; $user->toRawArray(); // 'updated_at' => Time object (bug) Solution: - Add DateTimeInterface check at the top of the convert closure in toRawArray(), converting DateTime objects to strings via __toString() - Always run attributes through convert closure in the !onlyChanged path instead of returning $this->attributes directly - Apply convert closure to non-recursive changed values too Ref: #8302
1 parent 2a1c348 commit b7f0796

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

system/Entity/Entity.php

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,11 @@ public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recu
233233
public function toRawArray(bool $onlyChanged = false, bool $recursive = false): array
234234
{
235235
$convert = static function ($value) use (&$convert, $recursive) {
236+
// Always convert DateTime objects to string for raw output
237+
if ($value instanceof DateTimeInterface) {
238+
return (string) $value;
239+
}
240+
236241
if (! $recursive) {
237242
return $value;
238243
}
@@ -261,9 +266,7 @@ public function toRawArray(bool $onlyChanged = false, bool $recursive = false):
261266

262267
// When returning everything
263268
if (! $onlyChanged) {
264-
return $recursive
265-
? array_map($convert, $this->attributes)
266-
: $this->attributes;
269+
return array_map($convert, $this->attributes);
267270
}
268271

269272
// When filtering by changed values only
@@ -335,7 +338,7 @@ public function toRawArray(bool $onlyChanged = false, bool $recursive = false):
335338
}
336339

337340
// non-recursive changed value
338-
$return[$key] = $value;
341+
$return[$key] = $convert($value);
339342
}
340343

341344
return $return;

0 commit comments

Comments
 (0)