Laravel Blade Foreach First Element Example
Hello Developer,
This article will provide an example of laravel foreach loop first. If you have a question about laravel foreach loop first then I will give a simple example with a solution. I would like to share with you laravel blade foreach first element. This article will give you a simple example of laravel blade foreach first item.
Laravel Blade offers a @foreach loop for rendering array data. If you need to determine whether an element is the first or last one and apply a class or other actions accordingly, you can utilize $loop->first and $loop->last.
Here, i will give you simple examples that way you can use $loop->first and $loop->last in your blade file.
Example 1:
you can see the simple blade file code:
@foreach ($users as $user)
@if ($loop->first)
This is the first item.
@endif
@if ($loop->last)
This is the last item.
@endif
<p>This is user {{ $user->name }}</p>
@endforeach
Example 2:
you can see the simple blade file code:
<ul>
@foreach ($users as $user)
<li @if ($loop->first) class="active" @endif>
{{ $user->name }}
</li>
@endforeach
</ul>
Example 3:
you can see the simple blade file code:
<ul>
@foreach ($users as $user)
<li @if ($loop->last) class="active" @endif>
{{ $user->name }}
</li>
@endforeach
</ul>
I hope it can help you...