Skip to content
Advertisement

How to display something only for the first item from the collection in Laravel Blade template

I have a @foreach loop in the Blade template and need to apply special formatting to the first item in the collection. How do I add a conditional to check if this is the first item?

@foreach($items as $item)
    <h4>{{ $item->program_name }}</h4>
@endforeach`

Advertisement

Answer

SoHo,

The quickest way is to compare the current element with the first element in the array:

@foreach($items as $item)
    @if ($item == reset($items )) First Item: @endif
    <h4>{{ $item->program_name }}</h4>
@endforeach

Or otherwise, if it’s not an associative array, you could check the index value as per the answer above – but that wouldn’t work if the array is associative.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement