Sidart's avatar
Level 12

Opinions about using Storage inside a controller

Hello everyone, I was just working on a project and I am handling an image upload/Update situation for a post inside my Posts Controller.

My question is mostly about if it's "okay" or not using Storage inside my controller or make a helper class to handle this situation

This is my update function inside my PostsController

 protected function update(array $data, $id)
{   
    $post = Post::findOrFail($id);
    
    if (isset($data['image'])) {

        if (Storage::disk('public')->exists($post->image)) {
            Storage::disk('public')->delete($post->image);
        };

        $image = $this->uploadImage($data['image']);

        unset($data['image']);

        $data = $data + $image;
        
    }

    $post->update($data);
    
    return response()->json([
        'updated' => true
    ]);
}

This is the UploadImage function inside my PostsController

 protected function uploadImage($image)
{   
    return [
        'image' => $image->storeAs('posts', $image->getClientOriginalName(), 'public')
    ];
}

Everything is built with TDD and is working as expected, just more of an opinion situation.

0 likes
2 replies
Talinon's avatar
Talinon
Best Answer
Level 51

@sidirgot

Short answer: it's okay.

Long answer: Most developers strive to keep controllers from getting "fat" with code. Personally, I would likely create a helper class that the controller invokes to handle. I would try my best to name the class to something that describes it's role.

Bottom line - it really doesn't matter; you'll get the same result either way. This all comes down to structure and being consistent with it. If you're working with a team, you all should be on the same page as to what level of extraction is to be expected from everyone contributing to the code base.

Since you're practising TDD, you can confidently refactor away and play around with what works best for you.

1 like
Sidart's avatar
Level 12

You are probably in my head because that is what is going through my head at the moment.

My experience says that structure-wise it should be in a helper class or even in a trait with more logic through in because other controllers do handle image uploads.

So my gut feeling which is saying that I should refactor is right.

Thanks for your input @talinon.

Please or to participate in this conversation.