Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> @endforeach` 
like image 915
SoHo Avatar asked Nov 25 '15 16:11

SoHo


People also ask

What is __ In Laravel blade?

Laravel later introduced a great helper function __() which could be used for JSON based translations. For instance, in your blade files, {{ __('The Web Tier') }} Whereas “The Web Tier” is added in a JSON file inside of resources/lang directory i.e {locale}.json likeso, {

What is the advantage of Laravel blade template?

The main advantage of using the blade template is that we can create the master template, which can be extended by other files.

What is Template inheritance in Laravel blade?

A templating engine makes writing frontend code easier and helps in reusing the code. All the blade files have a extension of *. blade.


2 Answers

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

like image 105
Shannon Matthews Avatar answered Sep 25 '22 22:09

Shannon Matthews


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.

like image 38
Liam Wiltshire Avatar answered Sep 22 '22 22:09

Liam Wiltshire