Search code examples
laravel-7

How to make multi images with the same id in Laravel 7


I'm making a product image upload form which results in many images belonging to one product id. How do I do that?

For uploading multiple images, it has been successful, but the product id is still separate.

This my controller:

public function store(ProductRequest $request,$id) {
    if ($request->hasFile('photo')){

        $photos = $request->file('photo');

        foreach ($photos as $photo) {

            $data= $request->all();

            $data['slug'] = Str::slug($request->name);
            $product=Product::create($data);

            $uploadphoto = [
                'products_id' => $product->id,
                'photos' => $photo->store('assets/product','public')
            ];
             ProductGallery::create($uploadphoto);
        }
    }else{
        return "image not found";
    }

    return redirect()->route('dashboard-product');

}

Solution

  • You are creating product inside of foreach that will create multiple products. If you need only one product keep the code of creating product, outside of foreach.

    public function store(ProductRequest $request,$id) {
        if ($request->hasFile('photo')){
            
            $photos = $request->file('photo');
    
            $data= $request->all();
    
            $data['slug'] = Str::slug($request->name);
            $product=Product::create($data);
    
    
    
            foreach ($photos as $photo) {
                $uploadphoto = [
                    'products_id' => $product->id,
                    'photos' => $photo->store('assets/product','public')
                ];
                 ProductGallery::create($uploadphoto);
            }
    
    
    
        }else{
            return "image not found";
        }      
        
        return redirect()->route('dashboard-product');
    
    }