简体   繁体   中英

How to loop a certain number of times regardless the number of records received (Laravel)

I have the following queries:

      @php
     $age_id = \App\Goalage::where('goal_id',$cat_fil->id)->pluck('age_id');
     $age_name = \App\Age::wherein('rangeid',$age_id)->groupby('rangeid')->get();
     @endphp

And the following If condition and foreach:

                   @if(count($age_name) > 4 ) 
                           @foreach($age_name as $agename)
                        <button type="button" class="btn btn-outline-primary btn-sm-new mr-1"> 
                         {{$agename->agerange}} yrs
                        </button>
                          @endforeach
                     <a href="{{some.route}}">Click here for more than 4 results <a>
                  @else
                  //same code but will show 4 results or less

                   @endif

How do I change the below syntax to only loop/show the first 4 results in the foreach, even if there was more?

@foreach($age_name as $agename)

You can do something like this to break the loop after 4 iterations
Add this in the foreach loop

  @if($loop->iteration > 4)

    @break

  @endif

Alternatively You can do this in your case for Laravel 5.2

@php
    $count = 0;
@endphp
@foreach($age_name as $agename)
    @if($count >= 4 )
        @break
    @endif
    <button type="button" class="btn btn-outline-primary btn-sm-new mr-1"> 
    {{$agename->agerange}} yrs
    </button>
    @php
     $count++;
    @endphp
@endforeach

Use take() or limit() to extract certain amount of records from the query:

$age_name = \App\Age::wherein('rangeid',$age_id)->groupby('rangeid')->take(4)->get();

Or

$age_name = \App\Age::wherein('rangeid',$age_id)->groupby('rangeid')->limit(4)->get();

Edit:

Use $loop->iteration to get the current iteration of the loop and break when it reaches a certain iteration which in your case is 4 .

@if(count($age_name) > 4 ) 
  @foreach($age_name as $agename)
      @if($loop->iteration > 4)
          @break;
      @endif
      <button type="button" class="btn btn-outline-primary btn-sm-new mr-1"> 
      {{$agename->agerange}} yrs
      </button>
  @endforeach
      <a href="{{some.route}}">Click here for more than 4 results <a>
@else
   //same code but will show 4 results or less
@endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM