Skip to content

Commit c3bc516

Browse files
Fix embed models serialization
1 parent 456326b commit c3bc516

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/Eloquent/EmbedsRelations.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use MongoDB\Laravel\Relations\EmbedsMany;
99
use MongoDB\Laravel\Relations\EmbedsOne;
1010

11+
use MongoDB\Laravel\Relations\EmbedsOneOrMany;
1112
use function class_basename;
1213
use function debug_backtrace;
1314

@@ -85,4 +86,34 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re
8586

8687
return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation);
8788
}
89+
90+
/**
91+
* Determine if the given key is an embed relationship method on the model.
92+
*
93+
* @param string $key
94+
* @return bool
95+
*/
96+
public function isEmbedRelation($key)
97+
{
98+
return $this->isRelation($key)
99+
&& is_a($this->{$key}(), EmbedsOneOrMany::class, true);
100+
}
101+
102+
/**
103+
* @inheritDoc
104+
*/
105+
public function toArray()
106+
{
107+
$embeds = [];
108+
109+
foreach (array_keys($this->getAttributes()) as $key) {
110+
if ($this->isEmbedRelation($key)) {
111+
$embeds[] = $key;
112+
}
113+
}
114+
115+
$this->loadMissing($embeds);
116+
117+
return parent::toArray();
118+
}
88119
}

0 commit comments

Comments
 (0)