From c3bc5162d5a94a9660240430f43caf277757d458 Mon Sep 17 00:00:00 2001 From: florianJacques Date: Fri, 13 Jun 2025 11:21:19 +0200 Subject: [PATCH 1/2] Fix embed models serialization --- src/Eloquent/EmbedsRelations.php | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/Eloquent/EmbedsRelations.php b/src/Eloquent/EmbedsRelations.php index d5984b08e..c70830ab6 100644 --- a/src/Eloquent/EmbedsRelations.php +++ b/src/Eloquent/EmbedsRelations.php @@ -8,6 +8,7 @@ use MongoDB\Laravel\Relations\EmbedsMany; use MongoDB\Laravel\Relations\EmbedsOne; +use MongoDB\Laravel\Relations\EmbedsOneOrMany; use function class_basename; use function debug_backtrace; @@ -85,4 +86,34 @@ 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); + } + + /** + * @inheritDoc + */ + public function toArray() + { + $embeds = []; + + foreach (array_keys($this->getAttributes()) as $key) { + if ($this->isEmbedRelation($key)) { + $embeds[] = $key; + } + } + + $this->loadMissing($embeds); + + return parent::toArray(); + } } From 0b2c12c812ce1f13d399d88db7c61307537bb204 Mon Sep 17 00:00:00 2001 From: florianJacques Date: Fri, 13 Jun 2025 11:28:30 +0200 Subject: [PATCH 2/2] refactoring code --- src/Eloquent/EmbedsRelations.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Eloquent/EmbedsRelations.php b/src/Eloquent/EmbedsRelations.php index c70830ab6..257ce7777 100644 --- a/src/Eloquent/EmbedsRelations.php +++ b/src/Eloquent/EmbedsRelations.php @@ -7,7 +7,6 @@ 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; @@ -90,7 +89,8 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re /** * Determine if the given key is an embed relationship method on the model. * - * @param string $key + * @param string $key + * * @return bool */ public function isEmbedRelation($key)