How to break a foreach loop in laravel blade view?

Sagar Gautam picture Sagar Gautam · Jul 19, 2017 · Viewed 61k times · Source

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 ?

Answer

Alexey Mezenin picture Alexey Mezenin · Jul 19, 2017

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