Laravel如果元素在foreach循环中为null,如何跳过元素?

时间:2017-11-28 13:58:22

标签: php laravel-5 laravel-5.5

我想在每个类别中显示最新帖子。如果所有类别都不为null,则可以,但如果有空类Trying to get property of non-object错误。 (我的意思是如果类别没有任何帖子)

那么当item返回null时,如何传递thos类别post?

控制器;

$categories=Category::with('posts')->latest()->get();
return view('frontend.home',compact('categories');

刀片;

@foreach($categories as $category)

<div class="col-md-3">
  <div class="card text-white">
    <a href="#"> <img class="card-img"
       src="{{url('uploads/'.$category->posts->first()->featured_image)}}"  alt="Card image">                                             

      <div class="card-img-overlay">
      <h4 class="card-title">{{$category->category_name}}</h4>
      </div>
    </a>
  </div>
</div>

@endforeach

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可以简单地检查foreach中每个类别中是否有任何帖子,并将所有html放在if语句中

@foreach($categories as $category)
    @if( count($category->posts) )
        <div class="col-md-3">
          <div class="card text-white">
                <a href="#"> <img class="card-img" src="{{url('uploads/'.$category->posts->first()->featured_image)}}"  alt="Card image">                                             
          <div class="card-img-overlay">
              <h4 class="card-title">{{$category->category_name}}</h4>
          </div>
        </a>
      </div>
    </div>
    @endif
@endforeach

显示每个类别的帖子......

You can simply check if there are any posts in every category in the foreach and put all the html in the if statement

@foreach($categories as $category)
    @if( count($category->posts) )
        @foreach($category->posts as $post)
          <div class="col-md-3">
            <div class="card text-white">
                  <a href="#"> <img class="card-img" src="{{url('uploads/'.$post->featured_image)}}"  alt="Card image">                                             
            <div class="card-img-overlay">
                <h4 class="card-title">{{$category->category_name}}</h4>
            </div>
          </a>
        </div>
      </div>
      @endforeach
    @endif
@endforeach