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

Laravel How to skip elements if element is null in foreach loops?

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

那么当项目 returns 为 null 时,我该如何传递这些类别 post?

控制器;

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

Blade;

@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

有什么建议吗?

您可以简单地检查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