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

tristanisginger's avatar

Should a delete image function go in the controller or model

Hi

In an online course I am taking the instructor has put his deleteImage($imagePath) function in the BlogController where it is called, I would have expected it to go in the Post model.

Where should it go?

0 likes
5 replies
topvillas's avatar

It should go in an image model or repository.

1 like
martinbean's avatar
Level 80

@tristanisginger If you’re deleting an image, then image is an entity, so it should go in an ImageController as a destroy() method.

1 like
tristanisginger's avatar

@martinbean would you mind explaining the logic to me further please. I nearly understand which is when i'm at my most dangerous!

When a $post is destroyed how is an ImageController used to destroy an Image? Do I need an Image model?

I am using intervention/image to create thumbnails of uploaded images but an unsure if that impacts anything.

martinbean's avatar

@tristanisginger I’m not sure I follow, given I’m not following along the course with you.

Why have you been instructed to add a deleteImage() method if it’s in fact deleting a post?

I would normally create an Image model for uploaded images, and then use a foreign key to “add” an image to another model, such as a Post. But it sounds like the image’s filename is simply a column on your Post model, and the course you’re following deletes the image in a separate method when a post is deleted.

If this is the case, I’d instead listen for Post models being deleted and then delete the image then:

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        // ...
    ];

    public function boot()
    {
        parent::boot();

        Post::deleted(function ($post) {
            // Delete $post->image_filename from storage
        });
    }
}
tristanisginger's avatar

Thanks @martinbean for clearing that up.

Your assumption that the Post model has an image filename as a column is correct. When the post is deleted or the post's image changed a deleteImage() method is called to remove the files from the server.

It didn't seem logically right to me and I will refactor the code to include an Image model.

Please could you tell me why you'd use a listener to delete the image instead of using a seperate method?

Thanks

Please or to participate in this conversation.