attach images to product variants when creating new laravel product

You need to group your form controls so that when they are submitted, you know which images go with each product.

How can I group form elements

Change your blade to something like this

@foreach($ColorSizes as $ColorSize)
        <div >
            <input type="text" name="color[{{$loop->iteration}}]" value="{{$ColorSize->colorname}}">
            <span><input type="text" name="size[{{$loop->iteration}}]" value="{{$ColorSize->sizename}}"></span>
         <input type="text" name="title[{{$loop->iteration}}]" id="title"  value="" placeholder="Enter Title" required/>
         <span><input type="file" class="form-control" id="image" name="image[{{$loop->iteration}}][]" multiple/>

Then your PHP would change to something like this.

 public function variants(Request $request)

        $data = $request->all();
        foreach($data['title'] as $key => $value){
              $attribute = new \App\Variant;
              $attribute->title  = $value;
              $attribute->size = $data['size'][$key];
              $attribute->color = $data['color'][$key];

              $attributeID = $attribute->id;


                $store_file = [];
                // Get the correct file array based on key                    
                $files = $request->file("image.{$key}.*");
                foreach ($files as $file) {
                    $images = $file->store('public/photos');

                    $store_file[] = [
                        'filename' =>  $images,
                        'variant_id' =>  $attributeID



Also, I didn’t test this PHP so you might have to debug this line a little $files = $request->file('image.'.$key); to make sure it gets you the correct file array.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top