How to break a foreach loop in laravel blade view?
Asked Answered
W

6

65

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 ?

Wanting answered 19/7, 2017 at 11:43 Comment(1)
Use @break before @endifKeitloa
T
140

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
Thurgau answered 19/7, 2017 at 11:45 Comment(1)
@break will work similar to other usage of break in loops ?Wanting
I
6

you can break like this

@foreach($data as $d)
    @if($d === "something")
        {{$d}}
        @if(condition)
            @break
        @endif
    @endif
@endforeach
Inequality answered 19/7, 2017 at 11:47 Comment(0)
K
5

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
Keitloa answered 19/7, 2017 at 12:0 Comment(2)
this is what i was looking for $loop->last;Horner
@YasserCHENIK Glad to help you :)Keitloa
N
2

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

Noranorah answered 3/2, 2022 at 0:33 Comment(0)
M
1

This method worked for me

@foreach(config('app.languages') as $lang)
    @continue(app()->getLocale() === $lang['code'])
    <div class="col">
       <a href="#" class="btn w-100">
          {!! $lang['img'] !!}&nbsp;&nbsp;{{ $lang['name'] }}
       </a>
    </div>
@endforeach
Menses answered 18/5, 2023 at 11:57 Comment(0)
U
0
@foreach($data as $d)
    @if(condition==true)
        {{$d}}
        @break // Put this here
    @endif
@endforeach
Upper answered 20/2, 2021 at 11:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.