我一直试图弄清楚如何过滤我的foreach循环,只显示一个图像,如果我的帖子有一个。到目前为止,我一直在尝试不同的功能和@ifs,但无济于事。
这是我的控制器代码:
<div class="container">
<div class="row">
<div class="col-sm-6">
@foreach($posts as $post)
<div>
<h1>{{$post->title}}</h1>
<p>{{$post->body}}</p>
<img src="{{url('img', $post->image)}}">
</div>
<hr>
@endforeach
</div>
</div>
</div>
你可以使用一个简单的@if
:
@if ($post->image)
<img src="{{ url('img/' . $post->image) }}">
@endif
或者@isset
:
@isset ($post->image)
<img src="{{ url('img/' . $post->image) }}">
@endisset
您可以使用简单的@if
语句来查看当前image
的$post
属性是否已设置。这可能看起来像这样:
@foreach($posts as $post)
<div>
<h1>{{$post->title}}</h1>
<p>{{$post->body}}</p>
@if(!empty($post->image))
<img src="{{url('img', $post->image)}}">
@endif
</div>
<hr>
@endforeach
通过包含它,仅当属性不为空时才会显示<img>
元素。
正如另一个答案中所提到的,你可以用@if(!empty(...))
替换@isset(...)
来获得相同的结果。