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`
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, {
The main advantage of using the blade template is that we can create the master template, which can be extended by other files.
A templating engine makes writing frontend code easier and helps in reusing the code. All the blade files have a extension of *. blade.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With