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

ahmd_rmzn's avatar

How to store images from a WYSIWYG editor on the backend

Currently, I am using Spatie Media Library, and I save images to the database using the Livewire updated hook. However, I don’t think this is the best approach, as it can lead to many orphaned images remaining in the database.

I am looking for the most effective strategy or mechanism for handling images on the backend when working with WYSIWYG editors.

 public function updatedTextEditorImage()
    {
        $media = $this->model->addMedia($this->textEditorImage)->toMediaCollection('description-images');

        $this->dispatch('textEditorImageUploaded',  url: $media->getUrl())->self();
    }
0 likes
1 reply
LaryAI's avatar
Level 58

When dealing with images from a WYSIWYG editor, it's important to manage them efficiently to avoid orphaned files and ensure that only necessary images are stored. Here’s a strategy you can use to handle images more effectively:

  1. Temporary Storage: When an image is uploaded via the WYSIWYG editor, store it temporarily. This can be done using a temporary directory or a specific media collection for unconfirmed images.

  2. Track Usage: Keep track of which images are actually used in the content. This can be done by parsing the content before saving it to identify which images are referenced.

  3. Confirm and Move: Once the content is saved, move only the used images to the permanent storage location or media collection. Delete any unused images from the temporary storage.

  4. Cleanup: Implement a scheduled task or a cleanup script that periodically removes old, unused images from the temporary storage to prevent clutter.

Here’s a basic implementation outline using Spatie Media Library and Livewire:

Key Points:

  • Temporary Storage: Use a separate media collection for temporary images.
  • Content Parsing: Extract image URLs from the content to determine which images are used.
  • Media Management: Move only the used images to the permanent collection and clean up the rest.
  • Scheduled Cleanup: Regularly clean up the temporary storage to remove any leftover images.

This approach ensures that only necessary images are stored permanently, reducing the risk of orphaned images and keeping your storage clean.

Please or to participate in this conversation.