movepixels's avatar

Delete uploads

What is the best way to handle automatic deletion of files if deleting the record?

Example very minimal for this example like a photos table with some basic fields id, location(path to the upload file).

When I delete id = 7, I need to delete the file from "location" value also. So there are no straggling uploaded files that belong to no record.

I was thinking of using in the Photo.php model using the deleted hook.

public static function boot()
    {
        self::deleted(function($model){
            // record has been deleted so its now safe to delete the files related to this record
        });
    }

Thanks,

Dave

0 likes
1 reply
D9705996's avatar
D9705996
Best Answer
Level 51

@movepixels - hooking into eloquent events would be how I would approach this problem.

Personal preference is I would put the logic within a moddl observer but only because I usually have other logic for creating/updating and don't want to bloat my models

https://laravel.com/docs/5.7/eloquent#observers

You could also set up a scheduled task to delete any images without a corresponding model as a backup just in case but shouldn't be needed

1 like

Please or to participate in this conversation.