Laravel Blade Foreach Last Element Example

By Hardik Savani October 12, 2023 Category : Laravel

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...

Tags :
Shares