ItSolutionStuff.com

Laravel Blade Foreach Last Element Example

By Hardik Savani β€’ October 12, 2023
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

Laravel Blade Check if Array Key Exists Example

Read Now β†’
β˜…

Laravel Blade Check If Variable Exists or Not Example

Read Now β†’
β˜…

How to Call Controller Function in Blade Laravel?

Read Now β†’
β˜…

Laravel Blade @includeWhen and @includeUnless Example

Read Now β†’
β˜…

Laravel Blade Isset Else Example

Read Now β†’
β˜…

Laravel Blade If Multiple Conditions Example

Read Now β†’
β˜…

Laravel Blade If Condition Example

Read Now β†’
β˜…

Laravel nl2br Blade Directive Example

Read Now β†’
β˜…

How to Create Custom Blade Directive in Laravel?

Read Now β†’
β˜…

Laravel Blade Check If Variable is Set or Not Example

Read Now β†’
β˜…

How to Write PHP Code in Laravel Blade?

Read Now β†’
β˜…

Laravel - How to Check If Array is Empty in Blade?

Read Now β†’
β˜…

Laravel - How to Get .env Variable in Blade or Controller?

Read Now β†’
β˜…

Laravel Blade Check if View Exists or Not Example

Read Now β†’