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

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

@foreach($items as $item) <h4>{{ $item->program_name }}</h4> @endforeach` 
+12
source share
6 answers

Soho

The fastest 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 else, if it is not an associative array, you can check the index value according to the answer above, but this will not work if the array is associative.

+9
source

Laravel 5.3 provides the $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

+49
source

Just take the key value

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

The main problem with Liam Wiltshire's answer is performance, because:

  • reset ($ items) rewind the collection pointer $ items over and over in every loop ... always with the same result.

  • Both are $ item , and the result of reset ($ item) is objects, so $ item == reset ($ elements) requires a complete comparison of its attributes ... requiring more processor time.

A more efficient and elegant way to do this, as Shannon suggests, is to use the Blade $ loop variable:

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

If you want to apply a special format to the first element, perhaps you could do something like (using the ternary conditional operator ?:) :

 @foreach($items as $item) <h4 {!! $loop->first ? 'class="special"': '' !!}>{{ $item->program_name }}</h4> @endforeach 

Pay attention to the use of tags {!! and !!} instead of {{ }} to avoid encoding html double quotes around the special string.

Sincerely.

+1
source

In laravel 5.8, you can also do something like this:

 @foreach($items as $item) @if ($loop->first) This is the first iteration. @endif @endforeach 

docs: https://laravel.com/docs/5.8/blade#loops

0
source

To get the first element of a collection in Laravel, you can use:

 @foreach($items as $item) @if($item == $items->first()) {{-- first item --}} <h4>{{$item->program_name}}</h4> @else <h5>{{$item->program_name}}</h5> @endif @endforeach 
-2
source

All Articles