Laravel 9 Foreach Loop Variable Example

    In this article, we will see laravel 9 foreach loop variable example. Laravel provides a simple blade template that provides many directives to use directly in HTML code. Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. Laravel blade has a foreach directive.

    @foreach directive is the same as foreach loop. While iterating through a foreach loop, you may use the loop variable to gain valuable information about the loop. The $loop variable is used to get information about the first or last iteration through the loop.

    So, let's see foreach loop variable laravel 9, foreach loop in laravel 9 blade, laravel 9 foreach loop in the controller.

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif
 
    @if ($loop->last)
        This is the last iteration.
    @endif
 
    <p>This is user {{ $user->id }}</p>
@endforeach

    If you are in a nested loop, you may access the parent loop's $loop variable via the parent property.

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is the first iteration of the parent loop.
        @endif
    @endforeach
@endforeach
Read Also: Laravel 9 Pluck Method Example

    The index of the current loop iteration (starts at 0).

@php
$numbers = [1, 3, 5, 7, 9, 11];
@endphp

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

    The current loop iteration (starts at 1).

@php
$numbers = [1, 3, 5, 7, 9, 11];
@endphp

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

    The $loop variable also contains a variety of other useful properties:

Property Description
$loop->index The index of the current loop iteration (starts at 0).
$loop->iteration The current loop iteration (starts at 1).
$loop->remaining The iterations remaining in the loop.
$loop->count The total number of items in the array being iterated.
$loop->first Whether this is the first iteration through the loop.
$loop->last Whether this is the last iteration through the loop.
$loop->even Whether this is an even iteration through the loop.
$loop->odd Whether this is an odd iteration through the loop.
$loop->depth The nesting level of the current loop.
$loop->parent When in a nested loop, the parent's loop variable.

    You might also like:

Bình luận
Vui lòng đăng nhập để bình luận
Một số bài viết liên quan