该集合实例上不存在图像

时间:2019-06-28 17:16:18

标签: php laravel laravel-5

我正在尝试从数据库到视图的产品表中的图像行中显示多个图像,但是从Property [image] does not exist on this collection instance.循环中收到此错误@foreach(json_decode($products->image, true) as $product),但是我尝试了其他解决方案,但是他们不工作。

这是密码

控制器

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

    }

刀片视图

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

产品型号

   protected $table='products';
  protected $primaryKey='id';
  protected $fillable=['name','price','image','stock'];

public function images()
{
    return $this->belongsTo('App\product', 'image');
}

将提供任何帮助。

1 个答案:

答案 0 :(得分:0)

您的产品模型应如下所示,以具有多个图像:

protected $table='products';
protected $primaryKey='id';
protected $fillable=['name','price','image','stock'];

public function images() {
    return $this->hasMany('App\images');
}

您可能还需要添加密钥,以防它们不匹配,例如:

return $this->hasMany('App\images', 'product_id', 'id');

完成此操作后,您可以像这样遍历图像:

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