user9555022
user9555022

Reputation:

Loop through collection - target every item above a certain number

I'm looping through my collection to display all my data. Pretty standard stuff - nothing special.

I wan't to target and apply functionality to every element from number 9 onwards.

For example. The first 8 sessions are free, after that I want to append a button to the 9th+ ones to pay.

@foreach($sessions as $session)
   <input type="text" name="event" value="{{ $counsellingSession->event_start_time }}" class="form-control datetimepicker" >
@endforeach 

could i apply a class to all items in position 9 and above.

Upvotes: 0

Views: 361

Answers (3)

Syed Faisal
Syed Faisal

Reputation: 132

Simple solution for that is you can use the keys of array in loop,

@foreach($sessions as $key => $session)
    @if($key > 8)
        <input type="submit">
    @endif
    <input type="text" name="event" value="{{ $counsellingSession->event_start_time }}"
           class="form-control datetimepicker" >
@endforeach

Upvotes: 0

ali
ali

Reputation: 862

you can do the following:

 $count=0;
@foreach($sessions as $session)
  $count++;
   @if($count >=9)
     here apply your classs
   @else
     <input type="text" name="event" value="{{ $counsellingSession->event_start_time }}" class="form-control datetimepicker" >
   @endif
  @endforeach 

Upvotes: 0

Martin Bean
Martin Bean

Reputation: 39389

You could use the magic $loop variable Blade templates have in @foreach loops like this:

@foreach($sessions as $session)
    @if($loop->index > 8)
        <!-- Display payment button -->
    @endif
@endforeach

Documentation: https://laravel.com/docs/master/blade#loops

Upvotes: 2

Related Questions