Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break a foreach loop in laravel blade view?

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 ?

like image 915
Sagar Gautam Avatar asked Jul 19 '17 11:07

Sagar Gautam


People also ask

Can you break a foreach loop PHP?

To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.

Does Break exit foreach?

break ends execution of the current for , foreach , while , do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1 , only the immediate enclosing structure is broken out of.

What does blade mean in Laravel?

Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates.


3 Answers

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
like image 58
Alexey Mezenin Avatar answered Oct 21 '22 07:10

Alexey Mezenin


you can break like this

@foreach($data as $d)
    @if($d === "something")
        {{$d}}
        @if(condition)
            @break
        @endif
    @endif
@endforeach
like image 6
Bilal Ahmed Avatar answered Oct 21 '22 08:10

Bilal Ahmed


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
like image 5
Hiren Gohel Avatar answered Oct 21 '22 07:10

Hiren Gohel