diff --git a/src/Eloquent/DocumentModel.php b/src/Eloquent/DocumentModel.php index 965b1a444..c4297219d 100644 --- a/src/Eloquent/DocumentModel.php +++ b/src/Eloquent/DocumentModel.php @@ -754,4 +754,20 @@ public function refresh() return $this; } + + /** @inheritDoc */ + public function toArray() + { + $embeds = []; + + foreach (array_keys($this->getAttributes()) as $key) { + if ($this->isEmbedRelation($key)) { + $embeds[] = $key; + } + } + + $this->loadMissing($embeds); + + return parent::toArray(); + } } diff --git a/src/Eloquent/EmbedsRelations.php b/src/Eloquent/EmbedsRelations.php index d5984b08e..20e3ccc71 100644 --- a/src/Eloquent/EmbedsRelations.php +++ b/src/Eloquent/EmbedsRelations.php @@ -7,9 +7,11 @@ use Illuminate\Support\Str; use MongoDB\Laravel\Relations\EmbedsMany; use MongoDB\Laravel\Relations\EmbedsOne; +use MongoDB\Laravel\Relations\EmbedsOneOrMany; use function class_basename; use function debug_backtrace; +use function is_a; use const DEBUG_BACKTRACE_IGNORE_ARGS; @@ -85,4 +87,17 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation); } + + /** + * Determine if the given key is an embed relationship method on the model. + * + * @param string $key + * + * @return bool + */ + public function isEmbedRelation($key) + { + return $this->isRelation($key) + && is_a($this->{$key}(), EmbedsOneOrMany::class, true); + } } diff --git a/tests/EmbeddedRelationsTest.php b/tests/EmbeddedRelationsTest.php index 1c68e2d34..d5bef3ea7 100644 --- a/tests/EmbeddedRelationsTest.php +++ b/tests/EmbeddedRelationsTest.php @@ -972,4 +972,18 @@ public function testUnsetPropertyOnEmbed() $this->assertNull($user->addresses->get(0)->city); $this->assertSame('Kyoto', $user->addresses->get(1)->city); } + + public function testEmbedManyToArrayCast() + { + $user = User::create(['name' => 'John Doe']); + $user->addresses()->saveMany([new Address(['city' => 'London'])]); + + //Reload document + $user = User::where('name', 'John Doe')->first(); + $array = $user->toArray(); + + $this->assertIsString($array['addresses'][0]['id']); + $this->assertIsString($array['addresses'][0]['created_at']); + $this->assertIsString($array['addresses'][0]['updated_at']); + } }