SoHo SoHo - 1 year ago 90
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>

Answer Source


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download