Spread the love

Laravel blade provides easy way to iterate a long list array or loop using @foreach and @for. @foreach and @for both used same structure as php foreach and for. In this article i will show you to use @foreach and @for loop with example and also the $loop variable. Loop variable is always available inside the loop and we can access it using $loop object.

Here is the syntax for for loop

@for ($count = 0; $count < 10; $count++)
    The Counter value is {{ $i }}
@endfor

and syntax for foreach loop

@foreach ($posts as $post)
    <p>Title :  {{ $post->title }}</p>
@endforeach

as we can see syntax is equivalent to php for loop, forelse is also can be used if array is empty then we can show else block as below

@forelse ($posts as $post)
    <li>{{ $post->title }}</li>
@empty
    <p>No posts</p>
@endforelse

Using loop variable inside foreach

$loop variable is used inside the foreach loop to access the some useful information like first, last, count, index etc. Below is the list of use of 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.

Source of table from laravel

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

Let’s understand Laravel blade foreach, for and loop variable with example

Step 1: Create a fresh laravel project

composer create-project --prefer-dist laravel/laravel blog

Step 2: Add routes in routes/web.php

Create routes to call our controller and blade file in it.

routes/web.php

<?php
use Illuminate\Support\Facades\Route;
 
Route::get('/example',function(){
 
 $posts=[["title"=>"test","id"=>"1"],["title"=>"test2","id"=>"2"]];
 return view("example-view",["posts"=>$posts]);
});

Step 3: Create View File

Now, create a example-view.blade.php in resource/views folder.

@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>
 <p>Title : {{ $post['title']}} </p>
@endforeach

Leave a Reply