You are viewing the documentation for an older version of this package. You can check the version you are using with the following command:
composer show spatie/laravel-medialibrary
Using a custom file removal strategy
By default, files will be stored inside a directory that uses the id of its Media-object as a name. Given this default file and folder structure, the DefaultFileRemover option simply gets the root folder name and deletes it.
In cases where you need to use a custom directory structure, the DefaultFileRemover can cause problems. For example, if you have a directory structure like this:
Using the DefaultFileRemover will delete the entire 2023 directory, which is not what you want. So we would use a custom file remover to delete only the files that are no longer needed.
<?php
namespaceSpatie\MediaLibrary\Support\FileRemover;
useIlluminate\Contracts\Filesystem\Factory;
useSpatie\MediaLibrary\MediaCollections\Filesystem;
useSpatie\MediaLibrary\MediaCollections\Models\Media;
interfaceFileRemover
{
publicfunction__construct(Filesystem $mediaFileSystem, Factory $filesystem);
/*
* Remove all files relating to the media model.
*/publicfunctionremoveAllFiles(Media $media): void;
/*
* Remove responsive files relating to the media model.
*/publicfunctionremoveResponsiveImages(Media $media, string $conversionName): void;
/*
* Remove a file relating to the media model.
*/publicfunctionremoveFile(string $path, string $disk): void;
}
You may use create your own custom file remover by implementing the FileRemover interface.
There is also now a second option available within media library for file remover functionality. Based on the above directory structure, we can use FileBaseFileRemover.
// config/media-library.php/*
* The class that contains the strategy for determining how to remove files.
*/
'file_remover_class' => Spatie\MediaLibrary\Support\FileRemover\FileBaseFileRemover::class,
This strategy works by locating the exact path of the image and conversions, and explicitly removing those files only, instead of purging a base directory.