Laravel Blade Foreach Last Element Example
Hey Artisan,
This article will provide some of the most important example laravel foreach loop last. It's a simple example of laravel foreach loop last. you will learn laravel blade foreach last element. This example will help you laravel blade foreach last item. Alright, let’s dive into the steps.
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 Call Controller Function in Blade Laravel?
- Laravel Blade @includeWhen and @includeUnless Example
- Laravel Blade Isset Else Example
- Laravel Blade If Multiple Conditions Example
- Laravel Blade If Condition Example
- Laravel nl2br Blade Directive Example
- How to Create Custom Blade Directive in Laravel?
- Laravel Blade Check If Variable is Set or Not Example
- How to Write PHP Code in Laravel Blade?
- Laravel - How to Check If Array is Empty in Blade?
- Laravel - How to Get .env Variable in Blade or Controller?
- Laravel Blade Check if View Exists or Not Example