Skip to content

Commit

Permalink
Implement updateRepeater() for morphMany relations (#526)
Browse files Browse the repository at this point in the history
  • Loading branch information
daun committed Feb 8, 2020
1 parent 11ccd87 commit 26a0d2d
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/Repositories/Behaviors/HandleRepeaters.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,57 @@ public function updateRepeaterMany($object, $fields, $relation, $keepExisting =
}
}


public function updateRepeaterMorphMany($object, $fields, $relation, $morph = null, $model = null)
{
$relationFields = $fields['repeaters'][$relation] ?? [];
$relationRepository = $this->getModelRepository($relation, $model);

$morph = $morph ?: $relation;

$morphFieldType = $morph.'_type';
$morphFieldId = $morph.'_id';

// if no relation field submitted, soft deletes all associated rows
if (!$relationFields) {
$relationRepository->updateBasic(null, [
'deleted_at' => Carbon::now(),
], [
$morphFieldType => $object->getMorphClass(),
$morphFieldId => $object->id,
]);
}

// keep a list of updated and new rows to delete (soft delete?) old rows that were deleted from the frontend
$currentIdList = [];

foreach ($relationFields as $index => $relationField) {
$relationField['position'] = $index + 1;
if (isset($relationField['id']) && Str::startsWith($relationField['id'], $relation)) {
// row already exists, let's update
$id = str_replace($relation . '-', '', $relationField['id']);
$relationRepository->update($id, $relationField);
$currentIdList[] = $id;
} else {
// new row, let's attach to our object and create
unset($relationField['id']);
$newRelation = $relationRepository->create($relationField);
$object->$relation()->save($newRelation);
$currentIdList[] = $newRelation['id'];
}
}

foreach ($object->$relation->pluck('id') as $id) {
if (!in_array($id, $currentIdList)) {
$relationRepository->updateBasic(null, [
'deleted_at' => Carbon::now(),
], [
'id' => $id,
]);
}
}
}

public function updateRepeater($object, $fields, $relation, $model = null, $repeaterName = null)
{
if (!$repeaterName) {
Expand Down

0 comments on commit 26a0d2d

Please sign in to comment.