Undefined property: stdClass::$images

Viewed 1409

In products table I have image row which stores images of every product and looks like this in database ["4.jpg","5.jpg"] in each product. Now I want to display the product and the images which belongs to that product in the view but am stuck it shows an error Undefined property: stdClass::$images how can I fix this ?

Here are the codes

blade view

   @foreach($products as $product)
   @foreach($product->images as $image)
      <img src="{{url('images',$image->filepath)}}" alt="">
     @endforeach
     @endforeach

Controller

public function store(Request $request) 
{ 

$Input=$request->all();
$image=array();
if($files=$request->file('image')){
    foreach($files as $file){
        $name=$file->getClientOriginalName();
        $file->move('images',$name);
        $image[]=$name;

    }

} 
 product::create(array_merge($Input,
 [
'image' => json_encode($image),

])); 
return redirect()->back(); 

}

Any help will be appriciated.

2 Answers

In the controller you're saving it under image:

'image' => json_encode($image),

but in the view you're reading from images:

@foreach($product->images as $image)

so I'm guessing that should be $product->image. You didn't post the controller that renders the view so I'm guessing here.

for the error you're getting, I think it's because your product table has image as an attribute and you're trying to retrieve the images using images as a key.

you're implementing a bad design for your application by storing the images as an array.

since you have multiple images create a new table images with product_id as a foreign key.

Schema::create('images', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->dateTime('created_at');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        });

now, on your products and image modals add the relationships.

/* add this on your Product.php modal */
public function images()
{
  return $this->hasMany('App\Image');
}
/* add this on your Image.php modal */
public function product()
{
   return $this->belongsTo('App\Product');
}

now, to retrieve all images related to a certain product, you just need to call

@foreach($product->images() as $image)
      <img src="{{url('images',$image->filepath)}}" alt="">
@endforeach
Related