Stop the loop from repeating categories

Posted 1 month ago by untymage

I'd want show categories if their exist on the model looks like this:

  • Albums
    • album 1
    • album 2
  • Singles (if there is no items for this category it shouldnt display on the page at all)
@foreach($artist->albums as $album)
    
    @if($album->type=='Album')
    <div>Albums</div>
    @endif()

    @if($album->type=='Single')
    <div>Single</div>
    @endif()

    {{$album->title}} - {{$album->year}}

@endforeach

it will render multiple categories:

  • Albums
    • album 1
  • Albums
    • album 1
  • Singles
    • single1
  • Singles
    • single1

if i take the "Albums" element outside of loop then it shows categories no matters if they have items or not

Excepted:

  • Album
    • album 1
    • album 2
  • Single
    • single 1
    • single 2

if Single havent item then:

  • Album
    • album 1
    • album 2

Please sign in or create an account to participate in this conversation.