pedroroccon's avatar

Question: Resizing images in create and update method

Hello everyone! Thanks for the interest in my topic.

I have a question. To show you, Let's assume that I have a Product model and a Product controller. Let's assume that my Product model has the "image" field, that handles the image file name.

Everytime that I create or update a product, I need to upload and resize an image. I don't want to rewrite my code for every method that I need to upload and resize the product image. So I found the "Events" and "Commands", but I don't know which to use in this case (Events or Commands). Someone can help me with that?

My idea is register an "Event" or "Command" and then, call only the Event/Command on my controller, like this:

public function create(ProductRequest $request)
{
    $input = $request->all();
    $product = new Product();

    // Something like:
    // Event::fire(new ResizeProductImage($input['file']));
    // or:
    // $this->dispatch(new ResizeProductImage($input['file']));
    // I need that my Event/Command returns the file name ($filename). 
    // This way I can use the new file name in my "fill" method.
    
    $product->fill($input);
    $product->save();
}

Thanks!!

0 likes
2 replies
sapagat's avatar
sapagat
Best Answer
Level 3

Hi @pedroroccon , Think about Events and Jobs of tasks which you don't need a direct result, i.e, you will never use $value = Event:fire , etc.

I try, when it's possible, to divide the forms regarding to images from the ones with only text. This can help you handle images separtely from the other attributes. Can you do this?

If not, I would dispatch a job that handles the image upload with information about the product Id. Once uploaded, an event can be fired (ProductImageUploaded, for example) and from the Product service update the product with that Id and the filename.

1 like
pedroroccon's avatar

Hello @sapagat! I think that the idea to divide the forms is great! I was thinking a little about this question, and I'll separate my forms as you said. Thanks for the help!

Please or to participate in this conversation.