2017-11-28 3 views
0

各カテゴリの最新投稿を表示したいすべてのカテゴリがnullでない場合、そのOK、しかし空のカテゴリがある場合Trying to get property of non-objectエラー。 (カテゴリには投稿がありません)Laravel foreachループで要素がnullの場合、要素をスキップする方法はありますか?

アイテムがnullを返す場合、どのようにカテゴリ投稿を渡すことができますか?

コントローラ;

$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 

アドバイスはありますか?

+0

foreachの前、またはコントローラ自体の中で空のカテゴリを削除するには、array_filter()を使用してください。 –

答えて

0

あなたは、単にすべてのカテゴリに投稿はforeachの中にあるかどうかを確認し、すべてのカテゴリの投稿を表示する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 

内のすべてのhtmlを置くことができる...

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 
+0

も同様ですが、1つの投稿は消えます。 –

+0

あなたは最初の()...のみを表示するのでカテゴリ - >投稿を繰り返す必要があります... – shushu304

+0

私はexmapleコードを追加しました – shushu304

関連する問題