ItSolutionStuff.com

Laravel Blade Foreach First Element Example

By Hardik Savani • October 12, 2023
Laravel

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

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 use Carbon in Laravel Blade or Controller File?

Read Now →

How to Call Controller Function in Blade Laravel?

Read Now →

Laravel Blade @includeWhen and @includeUnless Example

Read Now →

Laravel Blade Include File If Exists Example

Read Now →

Laravel Include Blade File with Data Example

Read Now →

Laravel Blade Include File Example

Read Now →

Laravel Blade @unless Directive Example

Read Now →

Laravel Blade Empty Directive Example

Read Now →

Laravel Blade Isset Else Example

Read Now →

Laravel Blade Foreach Loop Example

Read Now →

Laravel Blade Switch Case Statement Example

Read Now →