When I edit product, I'm trying to edit multiple images also, so if I upload new images the old images should be replaced by the new ones but now if I upload images I'm getting an error Property [filename] does not exist on this collection instance."
and the old images are not deleted but the new images have been added. There are products and ProductsPhoto tables that are related, in ProductsPhoto table there is a filename column, and product_id column. How can I replace the old images with the new ones when editing a product?
My code.
Blade template
<input multiple="multiple" name="photos[]" type="file">
Controller
public function update(Request $request)
{
$product = Product::with('ProductsPhoto')->find($request->product_id,'id');
if ($request->hasFile('photos')){
//Add the new photo
foreach ($request->photos as $photo) {
$filename = $photo->store('public/photos');
ProductsPhoto::create([
'product_id' => $product->id,
'filename' => $filename
]);
}
$oldFilename = $product->ProductsPhoto->filename;
//Update the database
$product->ProductsPhoto->filename = $filename;
//Delete old photo
Storage::delete($oldFilename);
}
$product->save();
}