Using the $loop variable in foreach loops in Laravel Blade

  13987 views   1 year ago Laravel

Laravel provides simple blade template which provides many directive to use direct in html code. With blade engine you can write core PHP code with @php directive. In Blade, you can also use loop directive like @for, @foreach, @forelse and @while instead of loop condition. While looping, you may use $loop variable for valuable information.

In this article, we will show $loop variable and its properties to get many useful information.

If you want to check whether it is first or last iteration of the loop, then you may use this.

@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp

@foreach ($numbers as $number)
    @if ($loop->first)
        {{ $number }} {{-- 3 --}}
    @endif

    @if ($loop->last)
        {{ $number }} {{-- 6 --}}
    @endif
@endforeach


You may get the index of the loop, which starts from 0.

@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp

@foreach ($numbers as $number)
    @if ($loop->index == 2)
        {{ $number }} {{-- 8 --}}
    @endif
@endforeach

or the iteration of the loop, which starts from 1.

@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp

@foreach ($numbers as $number)
    @if ($loop->iteration == 3)
        {{ $number }} {{-- 8 --}}
    @endif
@endforeach

If you want to get remaining iterations of the loop, you may use.

@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp

@foreach ($numbers as $number)
    @if ($loop->iteration == 1)
        {{ $loop->remaining }} {{-- 5 --}}
    @endif
@endforeach

You may use count property to get total number of items in the array.

@php
$numbers = [3];
@endphp

@foreach ($numbers as $number)
    {{ $loop->count }}
@endforeach

Same way you may find whether the current iteration is even or odd.

@php
$numbers = [3, 2, 8, 12, 2, 6];
@endphp

@foreach ($numbers as $number)
    @if ($loop->even)
        {{ $number }}
    @endif
@endforeach

If you are iterating loop within loop, you may get the depth of the loop.

@foreach ($users as $user)
    @foreach ($user['articles'] as $article)
        {{ $loop->depth }}
    @endforeach
@endforeach

While looping internal loop, you may get parent loop details with parent property.

@foreach ($users as $user)
    @foreach ($user['articles'] as $article)
        {{ $loop->parent->iteration }}
    @endforeach
@endforeach

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]