Reputation: 9369
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 ?
Upvotes: 65
Views: 139445
Reputation:
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'] !!} {{ $lang['name'] }}
</a>
</div>
@endforeach
Upvotes: 1
Reputation: 21
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
Upvotes: 2
Reputation: 4066
you can break like this
@foreach($data as $d)
@if($d === "something")
{{$d}}
@if(condition)
@break
@endif
@endif
@endforeach
Upvotes: 6
Reputation: 933
@foreach($data as $d)
@if(condition==true)
{{$d}}
@break // Put this here
@endif
@endforeach
Upvotes: 0
Reputation: 5042
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
Upvotes: 5
Reputation: 163768
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
Upvotes: 141