joh
joh

Reputation: 238

Laravel property [filename] does not exist on this collection instance

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

Upvotes: 1

Views: 1504

Answers (1)

jcheron
jcheron

Reputation: 193

It seems that a product hasMany productsPhoto, so $product->ProductsPhoto is a collection, and not a photo!

I don't know how your entities are defined, especially Product and ProductPhoto classes: But you should delete the old collection of productsPhoto

$product->productsPhoto()->delete();

and save the new ones:

$newPhotos=[];
foreach ($request->photos as $photo) {
    $filename = $photo->store('public/photos');
    $newPhotos[] = new ProductsPhoto(['filename'=>$filename]);
} 
$product->productsPhoto()->saveMany($newPhotos);

Rather than trying to replace file names

Upvotes: 2

Related Questions