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

Laravel 5.3 provides a $loop variable in foreach loops.

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach

Docs: https://laravel.com/docs/5.3/blade#the-loop-variable


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.


Just take the key value

@foreach($items as $index => $item)
    @if($index == 0)
        ...
    @endif
    <h4>{{ $item->program_name }}</h4>
@endforeach