user3732216
user3732216

Reputation: 1589

Laravel Iterating Over Collection In View

I'm trying to iterate over a collection of classes for a student and need help making sure that the display of the class gets rendered the way it needs to. For the first class of the day for the day it needs to say "First Class" if its the last class of the day then it needs to say "Last Class" if its anything in between it needs to say Class #x where x represents the number of the class from the property.

I was wondering if this is a place I can use for example first() and last() in the collection but can't understand it in this context.

How do I need to complete the if statments.

@foreach($student->classes as $class)
    @if($class->class_number == 1)
        <p>{{ "First Class" }}</p>
    @elseif()
    @else
    @endif
@endforeach

Upvotes: 2

Views: 71

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

You should really use the the $loop variable here:

@foreach($student->classes as $class)
    @if ($loop->first)
        <p>{{ "First Class" }}</p>
    @endif

    @if ($loop->last)
       <p>{{ "Last Class" }}</p>
    @endif

    <p>{{ $loop->iteration." Class" }}</p>
@endforeach

Upvotes: 1

Related Questions