Delete avatar image file from local storage
In order to activate user avatars, I followed the instructions on this page https://github.com/jeffgreco13/filament-breezy. It works pretty good, except that the previously uploaded avatar image files remain undeleted after the user deletes or changes the avatar.
How to automatically delete the outdated avatar image file from the local storage when a user updates his avatar or a user account is removed by the super admin?
7 Replies
You can do this with a model observer. It’s a laravel feature.
Thanks for your response! The avatar url is saved to the db when clicking the Update button in the user profile page, no matter adding or removing the user avatar. Is it more logical to remove the old avatar file simultaneously?
Models have a lifecycle too. So, when th model is updating you can grab the old avatar path compare it to the new avatar path and if they aren’t equal then delete the old one.
The benefit of doing it with an observer is that should you even need to change it somewhere else in the app you don’t have to remember to implement the logic again.
Thanks again! From the steps to enable user avatars I learned from the web page mentioned previously, I don't see where the url of the old avatar is stored, i.e. the new avatar url is stored and replaces the old one in the db immediately after hitting the Update button, including avatar deletion. If removing the avatar image file from disk is not doable simutanesouly, the only way I could think of is comparing all the avatar files with all the user's avatar urls in the db and deleting unmatched ones then, which is quite resource comsuming, especially when there are thousands of avatar image files as the web site grows.
Thanks a lot! I've tried Method 1, the avatar file was successfully deleted when I clicked the "x" button and then the Update button. However, when I tried to set a new avatar, it threw the following error when hitting the Update button.
League\Flysystem\Filesystem::delete(): Argument #1 ($location) must be of type string, null given, called in /var/www/filament/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php on line 513
This error points to the line within the isDirty
condition.
I managed to eliminate the error message by changing the if condition from $user->isDirty('avatar_url')
to is_null($user->avatar_url)
. Is it good enough?Yes, if it's nullable