如何检查属性的foreach循环。 Laravel

问题描述 投票:1回答:2

我一直试图弄清楚如何过滤我的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>
php laravel
2个回答
0
投票

你可以使用一个简单的@if

@if ($post->image)
    <img src="{{ url('img/' . $post->image) }}">
@endif

或者@isset

@isset ($post->image)
    <img src="{{ url('img/' . $post->image) }}">
@endisset

https://laravel.com/docs/5.5/blade#control-structures


0
投票

您可以使用简单的@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(...)来获得相同的结果。

© www.soinside.com 2019 - 2024. All rights reserved.