How to display something only for the first item from the collection in Laravel Blade template
Solution 1
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.
Solution 2
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
Solution 3
Just take the key value
@foreach($items as $index => $item)
@if($index == 0)
...
@endif
<h4>{{ $item->program_name }}</h4>
@endforeach
Solution 4
As of Laravel 7.25, Blade now includes a new @once component, so you can do it like this:
@foreach($items as $item)
@once
<h4>{{ $item->program_name }}</h4> // Displayed only once
@endonce
// ... rest of looped output
@endforeach
Solution 5
Laravel 7.* provides a first()
helper function.
{{ $items->first()->program_name }}
*Note that I'm not sure when this was introduced. So, it may not work on earlier versions.
It is only briefly mentioned in the documentation here.
SoHo
Updated on January 12, 2022Comments
-
SoHo over 2 years
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`
-
SoHo over 8 yearsBoth, yours and @gumma-mocciaro solutions work in my case. This one is shorter.
-
Brnovich over 6 yearsWorked perfect for me !
-
bfontaine over 6 yearsThe question is about the Blade templating system; not Laravel itself.
-
David Harkness over 6 yearsThis will fail if the first item's index is not zero.
-
Gumma Mocciaro over 6 yearsThis will fail even if
$items
is not an array :). -
w2d over 6 yearsThe question is about LARAVEL Blade. Read the question
-
bfontaine over 6 yearsBlade is the template system included in Laravel. OP isn’t asking about Laravel as a whole but rather Blade itself. Your answer doesn’t address OP’s question, as you can guess from the downvotes and the others’ answers.
-
w2d almost 6 yearsThe question is : How to display something only for the first item from the collection in Laravel Blade template. There is LARAVEL in the question !!!
-
bfontaine almost 6 yearsThere is "laravel blade" in the question. Not "laravel" only.
-
Sheldon Scott almost 6 yearsExactly what I was looking for. Thanks for this!
-
w2d over 5 yearsThe answer with best note quotes Laravel 5.3 !