Laravel Blade foreach loop with Example

Laravel blade foreach loop example; In this tutorial, you will learn how to use foreach loop in laravel blade file. Loop is very important for array values to show in the blade file.

Laravel blade provides an easy way to iterate a long list array or loop using @foreach and @for. @foreach and @for both used the same structure as PHP foreach and for. The below example of foreach loop statement in laravel 5, laravel 6, laravel 7, Laravel 8, or laravel 9 apps.

Syntax:

The syntax for foreach loop:

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

Example:

Let’s understand Laravel blade foreach with example

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Blade Foreach Loop Example - codingdriver.com</title>
</head>
<body>
    @foreach ($users as $key => $user)
        This is index {{$key}} and user id is = {{ $user->id }}
    @endforeach
</body>
</html>

Using loop variable inside foreach

$loop the variable is used inside the foreach loop to access some useful information like first, last, count, index, etc. Below is the list of use variables.

$loop->indexThe index of the current loop iteration (starts at 0).
$loop->iterationThe current loop iteration (starts at 1).
$loop->remainingThe iterations remaining in the loop.
$loop->countThe total number of items in the array being iterated.
$loop->firstWhether this is the first iteration through the loop.
$loop->lastWhether this is the last iteration through the loop.
$loop->evenWhether this is an even iteration through the loop.
$loop->oddWhether this is an odd iteration through the loop.
$loop->depthThe nesting level of the current loop.
$loop->parentWhen in a nested loop, the parent’s loop variable.

Example of $loop variable

@foreach ($posts as $post)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>loop index {{ $loop->index}} </p>
@endforeach

I hope its works for you.

Leave a Comment