How to break foreach loop in laravel blade ?

laravel provides so many control structures for frontend development like if/else, switch, loops and blade directives like php, section and many more. Some years ago, I have posted a question about how to break foreach loop in laravel blade on some condition. I have got some really good answers and I want to share here.

We need break statement in while loops on frequent basis but sometime we need this statement in for/foreach loops as well. We need the break statement in order to stop the iteration if some condition is true.

As Alexey Mezenin mentioned in the answer, we can use @break, a blade directive provided by laravel to break the loop iteration. Another awesome blade directive is @continue, which can be used to skip the loop iteration when some condition is true.

According to official docs https://laravel.com/docs/5.5/blade#loops, We can end the loop or skip the current iteration like this:

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

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

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

We can use @break and @continue blade directive in single line to end or skip the current loop iteration.

@foreach ($users as $user)
    @continue($user->role == 1)

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

    @break($user->role == 5)
@endforeach

We can use same approach to end or skip the iteration for other loop directives like @for, @forelse, @while as well. It's pretty simple.


share :

Sagar Gautam

A Computer Engineer from Nepal.


Leave your Feedback