我想为帖子列表中的每个条目显示一个图像。图像的名称是唯一的文件名。它们都保存在数据库(MySQL)表中。每个帖子都有一张以上的图片。代码运行正常。除非有一个没有图像文件名的post。这是一种可能的情况,但我无法让代码正常工作。如果post没有现有的文件名,我想显示一个默认的文件名。下面是我的代码:
镜像逻辑:
/**
* Get a vehicle's top or main image data from the image table
*/
public function topImage($id)
{
$image = Vehiclefulldataimage::where('vehiclefulldatas_id', $id)
->orderBy('id', 'ASC')->first();
return $image;
}这是刀片式视图,帖子:
@if (count($posts) > 0)
@foreach($posts as $post)
<?php $imageFilename = (new \App\Models\Logic\Images)->topImage($post->id); ?>
<!--Item-->
<li>
<div class="preview">
@if ($imageFilename = 0)
<img src="{{ asset('images') . '/' . 'defaultImage.jpg' }}" alt="No photo">
@else
<img src="{{ asset('images') . '/' . $imageFilename->disk_image_filename }}" alt="{{ ucfirst($imageFilename->caption) . ' | ' . $post->title }}">
@endif
</div>
<div class="desc">
<h3>{{ str_limit($post->title, 100, '...') }}</h3>
</div>
</li>
<!--/Item-->
@endforeach
@endif这是我得到的错误信息:“正在尝试获取非对象的属性”
发布于 2020-03-25 20:16:32
谢谢大家。在查看了所有答案之后,我对代码进行了简单的修改。我修改了:@if ($imageFilename = 0)
收件人:@if ($imageFilename == null)
因此,我的代码现在看起来是:
@if (count($posts) > 0)
@foreach($posts as $post)
<?php $imageFilename = (new \App\Models\Logic\Images)->topImage($post->id); ?>
<!--Item-->
<li>
<div class="preview">
@if ($imageFilename == null)
<img src="{{ asset('images') . '/' . 'defaultImage.jpg' }}" alt="No photo">
@else
<img src="{{ asset('images') . '/' . $imageFilename->disk_image_filename }}" alt="{{ ucfirst($imageFilename->caption) . ' | ' . $post->title }}">
@endif
</div>
<div class="desc">
<h3>{{ str_limit($post->title, 100, '...') }}</h3>
</div>
</li>
<!--/Item-->
@endforeach
@endifhttps://stackoverflow.com/questions/60761301
复制相似问题