Skip to content

Commit

Permalink
fix(2.x): removable model
Browse files Browse the repository at this point in the history
  • Loading branch information
alexvenga committed Oct 30, 2023
1 parent 28937b3 commit 9b84bb2
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/Fields/MediaLibrary.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Collection;
use MoonShine\Fields\Image;
use MoonShine\Traits\Fields\FileDeletable;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

Expand Down Expand Up @@ -59,7 +60,7 @@ protected function resolveOnApply(): ?Closure
return static fn($item) => $item;
}

public function resolveAfterApply(mixed $data): mixed
protected function resolveAfterApply(mixed $data): mixed
{
$oldValues = request()->collect($this->hiddenOldValuesKey())->map(
fn($model) => Media::make(json_decode($model, true))
Expand All @@ -84,12 +85,21 @@ public function resolveAfterApply(mixed $data): mixed
return null;
}

protected function resolveAfterDestroy(mixed $data): mixed
{
$data
->getMedia($this->column())
->each(fn(Media $media) => $media->delete());

return $data;
}

private function removeOldMedia(HasMedia $item, Collection $recentlyCreated, Collection $oldValues): void
{
foreach ($item->getMedia($this->column()) as $media) {
if (
!$recentlyCreated->contains('id',$media->getKey())
&& !$oldValues->contains('id',$media->getKey())
!$recentlyCreated->contains('id', $media->getKey())
&& !$oldValues->contains('id', $media->getKey())
) {
$media->delete();
}
Expand Down

0 comments on commit 9b84bb2

Please sign in to comment.