猿问

未定义的属性:stdClass::$images

在产品表中,我有图像行,它存储每个产品的图像,["4.jpg","5.jpg"]在每个产品的数据库中看起来像这样。现在我想在视图中显示产品和属于该产品的图像但卡住了它显示错误Undefined property: stdClass::$images我该如何解决?


这里是代码


刀片视图


   @foreach($products as $product)

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

      <img src="{{url('images',$image->filepath)}}" alt="">

     @endforeach

     @endforeach

控制器


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


}

任何帮助都将得到认可。


慕工程0101907
浏览 167回答 2
2回答

jeck猫

对于您遇到的错误,我认为这是因为您的产品表具有image作为属性,并且您正尝试使用images作为键来检索图像。通过将图像存储为数组,您正在为您的应用程序实现一个糟糕的设计。由于您有多个图像,因此创建了一个images以 product_id 作为外键的新表。Schema::create('images', function (Blueprint $table) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->bigIncrements('id');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->string('name');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->dateTime('created_at');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');&nbsp; &nbsp; &nbsp; &nbsp; });现在,在您的产品和图像模式上添加关系。/* add this on your Product.php modal */public function images(){&nbsp; return $this->hasMany('App\Image');}/* add this on your Image.php modal */public function product(){&nbsp; &nbsp;return $this->belongsTo('App\Product');}现在,要检索与某个产品相关的所有图像,您只需要调用@foreach($product->images() as $image)&nbsp; &nbsp; &nbsp; <img src="{{url('images',$image->filepath)}}" alt="">@endforeach

不负相思意

在控制器中,您将其保存在image:'image'&nbsp;=>&nbsp;json_encode($image),但在您阅读的视图中images:@foreach($product->images&nbsp;as&nbsp;$image)所以我猜应该是$product->image。您没有发布呈现视图的控制器,所以我在这里猜测。
随时随地看视频慕课网APP
我要回答