【问题标题】:Undefined property: stdClass::$images未定义的属性:stdClass::$images
【发布时间】:2019-06-29 21:55:56
【问题描述】:

在产品表中,我有一个图像行,它存储每个产品的图像,并且在每个产品的数据库["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(); 

}

如有任何帮助,将不胜感激。

【问题讨论】:

  • 你是如何生成$products的?该变量的转储是什么?
  • 我正在从这里生成产品product::create(array_merge($Input, [ 'image' =&gt; json_encode($image), ]));@Watercayman

标签: php laravel laravel-5


【解决方案1】:

在控制器中,您将其保存在image

'image' => json_encode($image),

但在你从images阅读的视图中:

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

所以我猜应该是$product-&gt;image。您没有发布呈现视图的控制器,所以我在这里猜测。

【讨论】:

  • 这给出了一个错误"Invalid argument supplied for foreach()@swordbeta
  • @user11710915 你事先 json_decode 了吗?您不能循环遍历字符串。如果您不这样做:@foreach(json_decode($product-&gt;image) as $image) 可能会这样做。
  • 是的,我以前做过,但它不起作用@swordbeta
  • 我尝试了 json_decode 并得到了错误 Property [image] does not exist on this collection instance. @swordbeta
【解决方案2】:

对于您遇到的错误,我认为这是因为您的产品表具有 image 作为属性,并且您尝试使用 images 作为键来检索图像。

您通过将图像存储为数组来为您的应用程序实现一个糟糕的设计。

由于您有多个图像,请创建一个新表 images,并将 product_id 作为外键。

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

现在,在您的产品和图像模式上添加关系。

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

现在,要检索与某个产品相关的所有图像,您只需调用

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

【讨论】:

  • 它不是将图像存储在图像表中,而是将图像存储在产品中->图像行@Djellal Mohamed Aniss
  • 我知道,我建议您为您的案例创建一个单独的表格
  • 我以前这样做过,我创建了图像表并与产品建立了关系,但不知道如何在数据库中显示它们,所以我问了一个问题,有人给出了 json_encode 答案现在我有json_encode 和图片都与产品相关,但无法正常工作 @Djellal Mohamed Aniss
  • json_encode 在数据库中显示图像但不在视图中显示它们但(图像->关系)无法将图像存储在图像表中我不知道为什么@Djellal Mohamed阿尼斯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-29
  • 1970-01-01
  • 2016-04-20
  • 2019-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多