我想为帖子列表中的每个条目显示一个图像。图像的名称是唯一的文件名。它们都保存在数据库(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-20 16:29:32
尝试以下代码:您正在使用赋值运算符而不是比较运算符
//@if (count($posts) > 0)
@if (!$posts->isEmpty())
@foreach($posts as $post)
<?php $imageFilename = (new \App\Models\Logic\Images)->topImage($post->id); ?>
<!--Item-->
<li>
<div class="preview">
//@if ($imageFilename = 0) this is an assignment operator not comparison operator
@if ($imageFilename->isEmpty())
<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-20 16:17:55
检查您正在执行的if statement....what there is a assignment and not a condition test...you可以包含column..with一个指向默认图像路径的字符串将其设置为default...then load it...as default image..and
发布于 2020-03-20 16:37:35
上面的所有答案都解决了你的问题。然而,我建议你通过使用Laravel的特性,转变器来解决这个问题。
https://laravel.com/docs/5.8/eloquent-mutators
Laravel赋值符使您可以格式化或修改Model属性。
只需在您的Vehiclefulldataimage模型中编写以下代码:
public function getImageAttribute($value)
{
//can write more logic here.
return $value ?: 'path/to/your/default/image';
}那么你就不再关心刀片模板的条件了。如果您的图像为空,则赋值函数将返回默认图像。所以,当你检索Vehiclefulldataimage实例时,赋值函数都能正常工作
https://stackoverflow.com/questions/60761301
复制相似问题