Skip to content

Commit

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

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

if (($diff = collect($values)->diff($existingObjects))->count() > 0) {
if (($diff = collect($values)->diff($existingObjectIds))->count() > 0) {
throw new SCIMException(
sprintf('One or more %s are unknown: %s', $this->attribute, implode(',', $diff->all())),
500
);
}

$object->saved(function (Model $model) use ($existingObjects, $users) {
$model->{$this->attribute}()->sync($existingObjects->all());
$model->setRelation($this->attribute, $users);
// Act like the relation is already saved. This allows running validations, if needed.
$object->setRelation($this->attribute, $existingObjects);

$object->saved(function (Model $model) use ($existingObjectIds) {
// Save relationships only after the model is saved. Essential if the model is new.
$model->{$this->attribute}()->sync($existingObjectIds->all());
});

}
Expand Down

0 comments on commit 1799fb4

Please sign in to comment.