Laravel Nova: Delete images from disk when content is modified and image is removed

  file-upload, laravel, laravel-nova, php, spatie

I am working with spatie media library to store my images. On the frontend site I am using Quill editor with Vue js to give users the option to modify their posts. The users on the frontend also have the option to upload images. Those images get send in base64 within the content.

On the server side I am checking if the content contains any images which are base64 encoded. If so, I store them via spatie media library and replace the base64 image tag with and an img tag which has the image link as source set. This happens BEFORE storing the content to the database.

Same procedure for updating the content. I check if all images which are stored for the post model in the spatie media library are still within the content. If not, delete those images. When there are new images I do the same procedure as described above. If the post gets deleted, the image will also be deleted.

Here you can read the "tutorial" on how to do this.

However, I don’t know how I can perform the same procedure when the admin is editing the content… Because I need to modify the query BEFORE the content gets stored as base64 images are way to long for my database.

Does anybody knows how to do this or had an similar problem?
I was thinking about observers. But there I have the problem that it is already to late. At the time the observer code is getting executed the content already got stored. This won’t work as my database only allows text with around 64.000 chars. I also don’t want to change that!

Second problem with observers will be that I will end up in a infinity loop because I need to call ->save() on my model which will trigger the observer again…

Any ideas on this? Basically I need to catch the SQL query before it will get executed.

Kind regards and thank you!

Source: Laravel

Leave a Reply