Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uminnkhantnaing's avatar

Spatie Media Library Deletes Entire Collection on S3 Instead of Single File

Hey everyone,

I'm using Spatie Media Library with S3 storage, and I’ve run into a critical issue when trying to delete a specific media file. Instead of removing just that one file, Spatie ends up deleting the entire media collection folder (including the conversions folder) on S3. However, the database records remain correct. (It works without any issue on localhost though).

Issue Details

  • When calling $media->delete(); on a specific file, all files in the collection disappear from S3.
  • The database still correctly retains the intended media records.
  • This happens regardless of how I query the media (by id, by uuid, by model relation).
  • If I upload a new file after deletion, Spatie correctly stores it, but the previously existing files are gone.

What I’ve Tried

1. Ensuring I'm Deleting the Correct File

  • Verified that $media->id matches the intended file.

  • Tried different ways to fetch the media:

    $media = $model->getMedia('collection_name')->firstWhere('id', $file['id']);
    $media = Media::find($file['id']);
    $media = Media::where('id', $file['id'])->first();
    
  • All methods result in the same unexpected behavior.

2. Checking for Soft Deletes

  • Tried $media->forceDelete(); but still faced the same issue.
  • My media table does not use soft deletes (deleted_at is not a column).

3. Checking for Event Listeners

  • Ran a grep search for deleting inside app/Listeners, app/Providers, and app/Models.
  • No custom event listeners affecting media deletion were found.

4. Manually Deleting Files from S3 Before Calling delete()

  • Tried explicitly deleting the file before deleting the media record:

    Storage::disk('s3')->delete($media->getPath());
    $media->delete();
    
  • But Spatie still deletes the whole collection.

5. Using forgetMedia() Instead of delete()

  • Called $model->forgetMedia($media->id);, but the issue persists.

6. Checking Disk Configuration in filesystems.php

  • The S3 disk is properly configured:

    'disks' => [
        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'visibility' => 'public',
        ],
    ]
    
  • config/media-library.php is also correctly set to use s3.

Expected vs. Actual Behavior

Expected: Only the specified media file should be deleted from S3.
Actual: The entire media collection folder (including conversions) is deleted from S3.

Environment Details

  • Laravel 10.x
  • Spatie Media Library 11.x
  • Storage: S3
  • Database: MySQL 8
  • Hosting: Laravel Forge

I’d really appreciate any insights into what might be causing this! Has anyone experienced something similar or found a workaround?

Thanks in advance!

0 likes
4 replies
LaryAI's avatar
Level 58

The issue you're experiencing with Spatie Media Library deleting the entire collection instead of a single file on S3 is unusual and could be caused by a few potential misconfigurations or bugs. Here are some steps and considerations to help you troubleshoot and resolve the problem:

  1. Check Spatie Media Library Configuration:

    • Ensure that your media-library.php configuration file is correctly set up, especially the disk_name and path_generator settings. The path generator should be generating unique paths for each media item.
  2. Verify S3 Permissions:

    • Double-check your S3 bucket permissions. Ensure that the IAM user or role used by your application has the correct permissions to delete individual files and not entire folders.
  3. Inspect the Path Generation:

    • Use logging to inspect the paths being generated for each media item. You can add a log statement before the deletion to see what path is being targeted:
      \Log::info('Deleting media path: ' . $media->getPath());
      
  4. Check for Custom Path Generators:

    • If you have implemented a custom path generator, ensure it is not causing the issue by generating paths that are too broad or incorrect.
  5. Update Packages:

    • Ensure that you are using the latest version of Spatie Media Library. There might be a bug that has been fixed in a newer release.
  6. Debugging with a Local Environment:

    • Since the issue does not occur locally, try to replicate your production environment locally as closely as possible. This includes using the same S3 bucket and IAM credentials.
  7. Review the Deletion Logic:

    • Look into the Spatie\MediaLibrary\MediaCollections\Models\Media model and the delete method to understand how the deletion is being handled. You might want to override this method temporarily to add more logging or to prevent the deletion of the entire folder.
  8. Consider Using a Custom Deletion Method:

    • As a temporary workaround, you can manually delete the file from S3 using the AWS SDK before calling the delete method on the media item:
      $s3 = \Storage::disk('s3');
      $s3->delete($media->getPath());
      $media->delete();
      
  9. Contact Spatie Support:

    • If none of the above solutions work, consider reaching out to Spatie's support or opening an issue on their GitHub repository with detailed information about your setup and the problem.

By following these steps, you should be able to identify the root cause of the issue and apply a suitable fix.

1 like
emmamegan's avatar

If your media collection is defined with the singleFile() method, adding a new file to this collection will trigger the deletion of the existing file. if the deletion process is not correctly handled, especially in an S3 environment, it might lead to unintended consequences, such as the removal of the entire directory or collection.

Recommended Actions:

Review Collection Configuration: Ensure that the media collection is configured appropriately. If you intend to allow multiple files, avoid using the singleFile() method. Conversely, if only one file should be present, ensure that the deletion logic is correctly implemented.

Check Deletion Logic: When deleting a media item, confirm that only the intended file is targeted for deletion. This involves verifying that the correct media instance is selected and that the deletion command is executed properly. S3 Configuration:

Amazon S3 treats each file as an individual object and doesn't inherently recognize directories in the traditional sense. Ensure that your application's logic accounts for this, preventing the deletion of pseudo-directories or multiple files unintentionally.

Update Dependencies: Ensure that you're using the latest versions of Laravel, Spatie's Media Library, and the AWS SDK. Updates often include fixes for known issues and improvements in handling file operations. Consult Documentation and Community:

Refer to Spatie's official documentation for best practices in managing media collections and deletions. Engaging with the community through forums or GitHub discussions can also provide insights and solutions from others who have faced similar challenges.

1 like
uminnkhantnaing's avatar

Thank you for your detailed response! I really appreciate your insights. Let me clarify a few things to give you more context about my setup:

My Media Collection Setup

  • I have a one-to-many relationship between the skus table and the sku_gallery media collection.
  • Each SKU can have multiple images stored under sku_gallery collection.
  • The collection is not using singleFile(). I can confirm that multiple images are correctly uploaded and retrieved without any issues.

Deletion Behavior Issue

  • The problem occurs when I try to delete a single media item within the collection using $media->delete();.
  • Instead of deleting just that one file, Spatie deletes the entire collection folder from S3, including the conversions folder.
  • The database records remain correct, meaning the media table correctly reflects the expected number of remaining images.

S3 Storage Structure

I've attached screenshots in the thread that show the directory layers on S3. Spatie correctly structures the media files inside their respective folders. However, after invoking $media->delete();, the whole folder (including its conversion images) disappears from S3, even though only one image was meant to be deleted.

What I’ve Verified

Media collection is not using singleFile()
Able to retrieve multiple images without any issues
Deletion command is targeting the correct media instance (verified by id, uuid, and other queries)
No custom event listeners interfering with the delete operation
Storage disk is correctly configured for S3 in filesystems.php
Database records remain correct after deletion, but files on S3 disappear

Next Steps

Do you think this might be related to how Spatie Media Library interacts with S3’s object structure? I suspect that it might be incorrectly interpreting the deletion operation at the folder level instead of the file level. Have you encountered anything similar?

Thanks again for your time and suggestions! Let me know if you need more details. 🙏

uminnkhantnaing's avatar
uminnkhantnaing
OP
Best Answer
Level 1

Solution Found ✅

I found the solution in one of my team members' source codes, which aligns with the implementation in the DefaultFileRemover class of the Spatie Media Library package in a specific version. It correctly ensures that only the specific media file and its related conversions/responsive images are deleted, without affecting other media files within the same collection.

If anyone faces a similar issue, I recommend checking the latest updates in the package or using a custom implementation based on the DefaultFileRemover class.

Updated Implementation

Resolution

Marking this as resolved. 🚀

Hope this helps anyone facing a similar issue!

1 like

Please or to participate in this conversation.