SoHo SoHo - 8 months ago 51
PHP Question

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>



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>

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.