@@ -319,31 +319,44 @@ protected function fromDecimal($value, $decimals)
319
319
return new Decimal128 ($ this ->asDecimal ($ value , $ decimals ));
320
320
}
321
321
322
+ /**
323
+ * Convert MongoDB objects to their string representations.
324
+ *
325
+ * This method converts MongoDB related objects (ObjectID, Binary, UTCDateTime)
326
+ * to their serialized representations, ensuring the values can be correctly
327
+ * serialized when the model is converted to JSON.
328
+ *
329
+ * @param mixed $value The value to convert
330
+ *
331
+ * @return mixed
332
+ */
333
+ protected function convertMongoObjects (mixed $ value ): mixed
334
+ {
335
+ if ($ value instanceof ObjectID) {
336
+ $ value = (string ) $ value ;
337
+ } elseif ($ value instanceof Binary) {
338
+ $ value = (string ) $ value ->getData ();
339
+ } elseif ($ value instanceof UTCDateTime) {
340
+ $ value = $ this ->serializeDate ($ value ->toDateTime ());
341
+ } elseif (is_array ($ value )) {
342
+ foreach ($ value as &$ nestedValue ) {
343
+ $ nestedValue = $ this ->convertMongoObjects ($ nestedValue );
344
+ }
345
+ }
346
+
347
+ return $ value ;
348
+ }
349
+
322
350
/** @inheritdoc */
323
351
public function attributesToArray ()
324
352
{
325
353
$ attributes = parent ::attributesToArray ();
326
354
327
- // Because the original Eloquent never returns objects, we convert
328
355
// MongoDB related objects to a string representation. This kind
329
356
// of mimics the SQL behaviour so that dates are formatted
330
357
// nicely when your models are converted to JSON.
331
- $ convertMongoObjects = function (&$ value ) use (&$ convertMongoObjects ) {
332
- if ($ value instanceof ObjectID) {
333
- $ value = (string ) $ value ;
334
- } elseif ($ value instanceof Binary) {
335
- $ value = (string ) $ value ->getData ();
336
- } elseif ($ value instanceof UTCDateTime) {
337
- $ value = $ this ->serializeDate ($ value ->toDateTime ());
338
- } elseif (is_array ($ value )) {
339
- foreach ($ value as &$ embedValue ) {
340
- $ convertMongoObjects ($ embedValue );
341
- }
342
- }
343
- };
344
-
345
358
foreach ($ attributes as $ key => &$ value ) {
346
- $ convertMongoObjects ($ value );
359
+ $ value = $ this -> convertMongoObjects ($ value );
347
360
}
348
361
349
362
return $ attributes ;
0 commit comments