N
N
Nikolay Erofeev2016-10-01 19:25:16
Laravel
Nikolay Erofeev, 2016-10-01 19:25:16

What is the correct way to handle a loop within a loop?

Hello. I've been writing an application for 2 days, maybe I'm stupid, but I can't figure out how to process a loop inside a loop. The task is this, there are songs, and favorites of songs. Let's say I have 3 songs in my favorites, and I need to highlight the songs that I have in my favorites.
inside the song cycle, I run 1 more cycle (from the favorites table), I need to compare 1 time for the song, is it in the favorites, then highlight. But the loop within the loop runs 3 times, right, yes, but how to do, only processed the selected equal to the song.

@foreach($musics as $music)
              
              <div class="list-music-karaoke">
                <div class="row">
                  <div class="col-10">
                    @foreach($musicsLiked as $musicLiked)
                      @if($musicLiked->liked_music_id == $music->id && $musicLiked->liked_music_id == $token)
                        <i class="fa fa-star" aria-hidden="true" data-music-id="{{ $music->id }}" data-music-cat-id="{{ $music->karaoke_category_id }}"></i>	
                      @else
                        <i class="fa fa-star-o" aria-hidden="true" data-music-id="{{ $music->id }}" data-music-cat-id="{{ $music->karaoke_category_id }}"></i>	
                      @endif	
                    @endforeach	
                  </div>
                  <div class="col-70">
                    <h3>{{ $music->karaoke_music_name }}</h3>
                    <p>{{ $music->karaoke_music_artist }}</p>
                  </div>
                  <div class="col-20">
                    <h2>{{ $music->karaoke_music_code }}</h2>
                    <h5>{{ $music->karaoke_music_type }}</h5>
                  </div>
                </div>
              </div>

            @endforeach

This is how the picture turns out
95eb9d0fd799472ebaeb5bae3c7f16e3.jpg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
root09, 2016-10-01
@root09

collection has a contains function, through it you check whether it contains the desired id, and you don’t need a cycle

D
D', 2016-10-01
@Denormalization

Make $musicsLiked an array with ID and check with in_array:

@if (in_array($music->id, $musicsLiked))
<i class="fa fa-star" aria-hidden="true" data-music-id="{{ $music->id }}" data-music-cat-id="{{ $music->karaoke_category_id }}"></i>	
@else
<i class="fa fa-star-o" aria-hidden="true" data-music-id="{{ $music->id }}" data-music-cat-id="{{ $music->karaoke_category_id }}"></i>	
@endif

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question