我在数据库中具有我的映像path
,现在,我正在尝试将图像输入我的HTML网格中。但是,当我尝试获取图像时,我会收到一个错误
属性[路径]在此集合实例上不存在。
但是,数据库中的表中有路径属性。我的模型是否一定是一个错误?我的模型对我来说似乎是正确的。无论如何,我在这里不做什么?
感谢您的关注
html
<figure>
<div class="snipcart-item block">
<div class="snipcart-thumb">
<a href="{{ route('product.view', $product->slug)}}"><img src="{{$product->images->path}}" alt=" " class="img-responsive" /></a>
<p>{{$product->name}}</p>
<h4>GH₵ {{ number_format($product->price,2) }} </h4>
</div>
<div class="snipcart-details top_brand_home_details">
<form action="#" method="post">
<fieldset>
</fieldset>
</form>
</div>
</div>
</figure>
图像
public function products()
{
return $this->belongsTo(Product::class);
}
product_images
public function images()
{
return $this->hasMany(Image::class);
}
您需要制作一个foreach
,因为它会给您收集。
因此,尝试显示它:
@foreach($product->images as $image)
@if($image->path)
<img src="{{ $image->path }}" alt=" " class="img-responsive" />
@else
<p>No image to display!</p>
@endif
@endforeach
希望这对您有帮助!
这是因为产品模型hasmany图像而发生的。为了到达路径属性,您应该这样做:
@foreach($product->images as $image)
{{$image->path}}
@endforeach
或在您的产品模型中执行此操作,然后更改数据库结构
public function image()
{
return $this->hasOne(Image::class);
}
我希望它有帮助。
如果您的路径没有任何问题,则以下是在Laravel Blade模板中显示图像的正确方法。
<img src="{{URL::asset('directory/name_of_image_file.file_format')}}">
db images
中没有字段 path
您的代码必须是:
<img src="{{$product->images->[you field in Db images]}}" alt=" " class="img-responsive" />
html
@foreach($products as $product)
<figure>
<div class="snipcart-item block">
<div class="snipcart-thumb">
<a href="{{ route('product.view', $product->slug)}}"><img src="{{$product->images->first()->path}}" alt=" " class="img-responsive" /></a>
<p>{{$product->name}}</p>
<h4>GH₵ {{ number_format($product->price,2) }} </h4>
</div>
<div class="snipcart-details top_brand_home_details">
<form action="#" method="post">
<fieldset>
</fieldset>
</form>
</div>
</div>
</figure>
@endforeach
<a href="{{ route('product.view', $product->slug)}}">
<img src="{{$product->images->first()->path}}" alt=" " class="img-responsive" />
</a>
$product->images
是一个集合,您需要从集合中获取图像。目前,我使用了将获取第一个图像的first()
,您可能需要根据您的方案循环浏览集合。您可能需要阅读有关答案的文章