Skip to content

Commit

Permalink
performance updates
Browse files Browse the repository at this point in the history
  • Loading branch information
arietimmerman committed Dec 11, 2024
1 parent f4c2af5 commit 42fb6fc
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/Attribute/MutableCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,11 @@ public function replace($value, Model &$object, ?Path $path = null)
$values = collect($value)->pluck('value')->all();

// Check if objects exist
$existingObjects = $object
->{$this->attribute}()
->getRelated()
::findMany($values)
$users = $object
->{$this->attribute}()
->getRelated()
::findMany($values);
$existingObjects = $users
->map(fn ($o) => $o->getKey());

if (($diff = collect($values)->diff($existingObjects))->count() > 0) {
Expand All @@ -58,9 +59,9 @@ public function replace($value, Model &$object, ?Path $path = null)
);
}

$object->saved(function (Model $model) use ($existingObjects) {
$object->saved(function (Model $model) use ($existingObjects, $users) {
$model->{$this->attribute}()->sync($existingObjects->all());
$model->load($this->attribute);
$model->setRelation($this->attribute, $users);
});

}
Expand Down

0 comments on commit 42fb6fc

Please sign in to comment.