Array of ObjectId not being casted to string when retrieving data
masterbater opened this issue · comments
Jason commented
Jason commented
Found a workaround
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use MongoDB\BSON\ObjectId;
class ConvertArrayObjectIdToString implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
// If the value is an array, convert each value to string
if (is_array($value)) {
return array_map(function ($item) {
// Convert MongoDB ObjectId to string
if ($item instanceof ObjectId) {
return (string) $item;
}
return $item;
}, $value);
}
// Convert MongoDB ObjectId to string
if ($value instanceof ObjectId) {
return (string) $value;
}
return $value;
}
public function set($model, $key, $value, $attributes)
{
// No transformation is applied when setting the attribute
if (is_array($value)) {
return array_map(function ($item) {
$objectId = new ObjectId($item);
return $objectId;
}, $value);
}
if ($value instanceof ObjectId) {
$objectId = new ObjectId($value);
return $objectId;
}
}
}