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

janthoegersen's avatar

delete file on disk when deleting related record in db

Hi all,

I have a file repository model which has a one to many relation with a file model (mysql). The file model has besides various attributes also a path attribute which points to an actual file on disk.

I'm struggling with how to build the logic to delete repositories and delete single files.

When deleting a repository then I want all related files to be deleted as well with the actual files on disk. If I use cascade deletion in mysql then i'm still left with the file on disk.

Same thing if I delete a record in the file table. I still have the file on disk.

I could set up a trigger on the delete signal on the file model so that when a instance of the file model is deleted then the file on disk is as well. However then I need to iterate trough all the related file records if I want to delete a repository.

If you have a suggestion could you then also describe where you would place the suggested code? Job, service, model etc.

Thank you in advance!

0 likes
2 replies
mortezapiri's avatar

before delete record access to your file path and write this unlink($file_path);

sr57's avatar
sr57
Best Answer
Level 39

You can't disable a trigger, so if you put a before trigger when you delete a repo, triggers will act on each file, and it works.

If you can have a lot a file per repo this solution is not to use, so do not use trigger (for file deletion) and put the logic in controller.

Please or to participate in this conversation.