How to break a foreach loop in laravel blade view?

PhpLaravelForeachBlade

Php Problem Overview


I have a loop like this:

@foreach($data as $d)
    @if(condition==true)
        {{$d}}
        // Here I want to break the loop in above condition true.
    @endif
@endforeach

I want to break the loop after data display if condition is satisfied.

How it can be achieved in laravel blade view ?

Php Solutions


Solution 1 - Php

From the Blade docs:

> When using loops you may also end the loop or skip the current > iteration:

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

Solution 2 - Php

you can break like this

@foreach($data as $d)
    @if($d === "something")
        {{$d}}
        @if(condition)
            @break
        @endif
    @endif
@endforeach

Solution 3 - Php

> Basic usage

By default, blade doesn't have @break and @continue which are useful to have. So that's included.

Furthermore, the $loop variable is introduced inside loops, (almost) exactly like Twig.

> Basic Example

@foreach($stuff as $key => $val)
     $loop->index;       // int, zero based
     $loop->index1;      // int, starts at 1
     $loop->revindex;    // int
     $loop->revindex1;   // int
     $loop->first;       // bool
     $loop->last;        // bool
     $loop->even;        // bool
     $loop->odd;         // bool
     $loop->length;      // int
 
    @foreach($other as $name => $age)
        $loop->parent->odd;
        @foreach($friends as $foo => $bar)
            $loop->parent->index;
            $loop->parent->parentLoop->index;
        @endforeach
    @endforeach 

    @break

    @continue

@endforeach

Solution 4 - Php

@foreach($data as $d)
    @if(condition==true)
        {{$d}}
        @break // Put this here
    @endif
@endforeach

Solution 5 - Php

Official docs say: When using loops you may also end the loop or skip the current iteration using the @continue and @break directives:

@foreach ($users as $user)
@if ($user->type == 1)
    @continue
@endif

<li>{{ $user->name }}</li>

@if ($user->number == 5)
    @break
@endif

@endforeach

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagar GautamView Question on Stackoverflow
Solution 1 - PhpAlexey MezeninView Answer on Stackoverflow
Solution 2 - PhpBilal AhmedView Answer on Stackoverflow
Solution 3 - PhpHiren GohelView Answer on Stackoverflow
Solution 4 - PhpLeonel KahameniView Answer on Stackoverflow
Solution 5 - PhpGerardo SortoView Answer on Stackoverflow