mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

Home Page:https://www.mongodb.com/compatibility/mongodb-laravel-integration

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Array of ObjectId not being casted to string when retrieving data

masterbater opened this issue · comments

  • Laravel-mongodb Version: 4.1.3
  • PHP Version: 8.3
  • Database Driver & Version:

Description:

I have an array of objectId when I retrieve the return data has $oid object instead of normal array string
image

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;
        }

    }
}