Skip to content
Advertisement

Laravel 7 Delete array or single image from db and disk – Deletes post but not associated images from db nor disk

In Laravel 7, I am have a task management app. I can upload tasks (posts if it were a blog) and images. I have a multiple image upload working as expected. When it comes time to delete a task, the task deletes just fine but the images are left in the database and in the disk which is public into a folder called task-images. Being new to Laravel, I am struggling on how to go about this. I tried to change the settings in the filesystem.php (which I will post with the commented out code) but that didn’t change the location as I had expected. In the end, I want to be able to delete the multiple images when I delete a post and also click delete on an individual image and delete that from both db and disk. I am using resource controller for all my task routes. I have no idea how to go about this and the tutorials that I have found don’t really address my specific issue. Any help would be greatly appreciated. Thank you in advance.

Here is my task controller at TaskController.php

JavaScript

filesystem.php (just the disks section)

JavaScript

in my individual show template, show.blade.php complete in case there is a code conflict.

JavaScript

In my Task model, Task.php, I have:

JavaScript

and finally my Image Model Image.php

JavaScript

If I am missing something, please let me know so I can edit my question. Again, thank you in advance for helping me with this issue. I have been scratching my head all week on this one. Cheers.

Edit After implementing boot functions in my model as suggested below, I received an error that an invalid argument was used for foreach. I ran a dd($task); and the following image shows the result. dd of $task on delete

Final Edit The answer below worked for my situation. I did have to edit some things to finalize the resolution: in Task.php I changed the foreach to the following.

JavaScript

I had declared image and not image in my model and that was causing a problem. Adding the ternary operator also helped the code not throw any errors.

In my TasksController.php I changed both the update and create functions with the same ternary operator as follows:

JavaScript

I hope this helps anyone else having the same issue. Thanks to @GrumpyCrouton and @lagbox for their help in resolving this as well as @user3563950 Without them, I would still by stratching my head for another couple of weeks.

Advertisement

Answer

on your AppImage class, implement to boot function with the following;

JavaScript

Also implement the boot method in AppTask class

JavaScript

Now on your TaskController implement the destroy method as follows;

JavaScript

As a bonus, learn Laravel model binding to ease the pain of finding an instance using findOrFail()

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement