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

SoHo picture SoHo · Nov 25, 2015 · Viewed 36.8k times · Source

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`

Answer

Shannon Matthews picture Shannon Matthews · Oct 16, 2016

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