Search code examples
phplaravelforeachbreaklaravel-5.8

How to break out of the foreach loop at first result and continue loop from the 2nd result


I have added this foreach for printing gallery images. But I don't want to print the gallery thumbnail inside the gallery images.

So I tried counting all the available images and initializing another variable $i=0. So if $i == 0, it means that the first image is thumbnail so it should break out of the foreach loop and restarts the loop to print the 2nd image.

Here is the code:

@php
    $i = 0;
    $len = count($gallery->galleryImages->where( 'gli_dimension', 'fullsize' ));
@endphp
@foreach( $gallery->galleryImages->where( 'gli_dimension', 'fullsize' ) as $img )
    @if ($i == 0)
        @php
           $i++;
           break;
        @endphp
    @endif
    <div style="display: none;">
        <a href="{{ \Illuminate\Support\Facades\Storage::url( $img['gli_path']) }}"
            data-fancybox="images-preview{{$gallery->gly_id}}"
            data-width="1500" data-height="1000"
            data-thumb="{{ \Illuminate\Support\Facades\Storage::url( $img['gli_path'] ) }}"
            data-caption="{{ $gallery->gly_title }}"></a>
    </div>
@endforeach

But now the problem is, it prints out the thumbnail and not the gallery images at all.

However, it was supposed to print all the gallery images, except the thumbnail.

So how to break out of the foreach loop at the first result and continue the loop from the 2nd result properly?


Solution

  • laravel provides loop variables

    Also when you use break it will jump out of a loop. So use continue instead of break

    break and continue

          @php
              $i = 0;
              $len = count($gallery->galleryImages->where( 'gli_dimension', 'fullsize' ));
          @endphp
          @foreach( $gallery->galleryImages->where( 'gli_dimension', 'fullsize' ) as $img )
              @if ($loop->first)
                  @php
                     $i++;
                     continue;
                  @endphp
              @endif
              <div style="display: none;">
                  <a href="{{ \Illuminate\Support\Facades\Storage::url( $img['gli_path']) }}"
                      data-fancybox="images-preview{{$gallery->gly_id}}"
            data-width="1500" data-height="1000"
            data-thumb="{{ \Illuminate\Support\Facades\Storage::url( $img['gli_path'] ) }}"
                      data-caption="{{ $gallery->gly_title }}"></a>
              </div>
          @endforeach