E
E
Evgeny Romashkan2018-04-26 01:37:28
Laravel
Evgeny Romashkan, 2018-04-26 01:37:28

How to implement the removal of images when removing a product from the store?

There is an online store. The database contains tables:
Categories; subcategories; products; product_images;
Product_images stores image paths.
What is the best way to implement the removal of the actual images when deleting a product.
Now I've set it up via Foreign keys so that when a category is deleted, its subcategories will be automatically deleted.
Behind the subcategory, its products are deleted, and after the products, information about their images from the database is also deleted.
Example:

$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

Is it worth it to use foreign keys and cascade in sql here for automatic deletion? Or it can implement all this already in the code, i.e. When deleting a category, first select and get all subcategories, then delete each in a cycle, in order to trigger the deleting and deleted events, which will respectively do the same with their products, which, respectively, with images.
( https://github.com/laravel/framework/issues/2536 - about calling delete* events)
This way, the deleted events will be fired in order, and you can easily add any of your own actions, such as physically deleting images.
It seems to me that having configured foreign keys to go through all this in the code additionally is stupid. Since it is possible to transfer then the removal completely into the code and get by with only it.
Wouldn't the removal option that I suggested above be a crutch?
At first I was confused that this would add a cycle in the destroy method of each model in this structure. However, as I understand it, the solution through foreign keys is not so easy to expand to the desired functionality.
The project is entirely educational. for the purpose of self-development and development of new technologies.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
entermix, 2018-04-26
@EvgeniiR

Well, database links won't let you delete an image, so you need to think through the logic in the application itself.
PS If you use MySQL - please note:
Why doesn't the MYSQL trigger work?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question