Skip to content

Commit

Permalink
Don't include soft deleted models as orphaned media (#3428)
Browse files Browse the repository at this point in the history
* Don't include soft deleted models as orphaned media

* In case a model is restored the media needs to stay around

* extract orphansQuery method
  • Loading branch information
patrickomeara authored Nov 3, 2023
1 parent 6a69de3 commit f464c82
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/MediaCollections/MediaRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,13 @@ public function getByCollectionName(string $collectionName): DbCollection

public function getOrphans(): DbCollection
{
return $this->query()
->whereDoesntHave('model')
return $this->orphansQuery()
->get();
}

public function getOrphansByCollectionName(string $collectionName): DbCollection
{
return $this->query()
->whereDoesntHave('model')
return $this->orphansQuery()
->where('collection_name', $collectionName)
->get();
}
Expand All @@ -108,6 +106,15 @@ protected function query(): Builder
return $this->model->newQuery();
}

protected function orphansQuery(): Builder
{
return $this->query()
->whereDoesntHave(
'model',
fn (Builder $q) => $q->hasMacro('withTrashed') ? $q->withTrashed() : $q,

Check failure on line 114 in src/MediaCollections/MediaRepository.php

View workflow job for this annotation

GitHub Actions / phpstan

Call to an undefined method Illuminate\Database\Eloquent\Builder::withTrashed().

Check failure on line 114 in src/MediaCollections/MediaRepository.php

View workflow job for this annotation

GitHub Actions / phpstan

Call to an undefined method Illuminate\Database\Eloquent\Builder::withTrashed().
);
}

protected function getDefaultFilterFunction(array $filters): Closure
{
return function (Media $media) use ($filters) {
Expand Down
23 changes: 23 additions & 0 deletions tests/Conversions/Commands/CleanCommandTest.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Spatie\MediaLibrary\MediaCollections\Exceptions\DiskDoesNotExist;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
Expand Down Expand Up @@ -352,3 +353,25 @@
'id' => $media->id,
]);
});

it('will not clean media items on soft deleted models', function () {
$testModelClass = new class () extends TestModel {
use SoftDeletes;
};

/** @var TestModel $testModel */
$testModel = $testModelClass::find($this->testModel->id);

$media = $testModel->addMedia($this->getTestJpg())->toMediaCollection('images');

$testModel->deletePreservingMedia();

$this->artisan('media-library:clean', [
'--delete-orphaned' => 'true',
]);

// This media should still exist.
$this->assertDatabaseHas('media', [
'id' => $media->id,
]);
});

0 comments on commit f464c82

Please sign in to comment.