artisticre's avatar

Multiple Image Add

I am working on adding product info, product thumbnail, and multiple images. I have the product info and thumbnail working fine. When it comes to the multiple images, its passing all the images from the form to the controller but when it inserts there is a problem. If I try to upload 4 images, it uploads 3. I think it has to do with the foreach but not sure how>?

$product->save(); 
              $product_id = $product->id;


              $multiimg = new MultiImg;

              $multiimg->product_id = $product_id;
              $multiimg->created_at = Carbon::now();

              $images = $request->file('multi_img');
              foreach($images as $img) {
                $filename = time() .'.'.$img->getClientOriginalExtension();
                $location = public_path('backend/uploads/products/multiple/'.$filename);
                Image::make($img)->resize(917,1000)->save($location);
                $multiimg->photo_name = $filename;
              }

        
              $multiimg->save();
0 likes
1 reply
frankielee's avatar

Have you tried to debug it by putting using the log?

Example:

 foreach($images as $i =>$img) {
 logger("storing image $i");
}

BTW, I think there are two other issues, which are:

  1. $filename =time() .'.'.$img->getClientOriginalExtension();
    • you might getting the same filename, if the code executes too fast.
  • you should use hashName() instead
  1.  `$multiimg->photo_name = $filename;`
    
    • you are only saving the last generated filename, is that a correct approach?

Ref:

  1. https://laravel.com/docs/9.x/filesystem#other-uploaded-file-information

Please or to participate in this conversation.