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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Blade Check if Array Key Exists Example
- Laravel Blade Check If Variable Exists or Not Example
- How to use Carbon in Laravel Blade or Controller File?
- How to Call Controller Function in Blade Laravel?
- Laravel Blade @includeWhen and @includeUnless Example
- Laravel Blade Include File If Exists Example
- Laravel Include Blade File with Data Example
- Laravel Blade Include File Example
- Laravel Blade @unless Directive Example
- Laravel Blade Empty Directive Example
- Laravel Blade Isset Else Example
- Laravel Blade Foreach Loop Example
- Laravel Blade Switch Case Statement Example