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');
}
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');
}