Performance: Control structures (@if, @foreach, @for)
These control structures affect how many DOM elements are rendered and how often the template engine processes loops and conditions, impacting page load and rendering speed.
@foreach($items->filter(fn($item) => $item->isActive()) as $item) <li>{{ $item->name }}</li> @endforeach
@foreach($items as $item)
@if($item->isActive())
<li>{{ $item->name }}</li>
@endif
@endforeach| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| @if inside @foreach loop | N condition checks, up to N DOM nodes | Up to N reflows if nodes inserted | Medium paint cost | [!] OK |
| Pre-filter collection before @foreach | Only active items processed | Fewer reflows proportional to filtered count | Lower paint cost | [OK] Good |
| Calling count() in loop condition | Repeated function calls each iteration | No direct reflows but CPU overhead | Low paint cost | [X] Bad |
| Store count() in variable before loop | Single function call per count | No extra reflows | Low paint cost | [OK] Good |
@if directive do in a Laravel Blade template?@if directive is used to check a condition and show content only when that condition is true.@foreach repeats content for each item, and @for repeats content a set number of times, so they do not match the description.@foreach loop in Laravel Blade?as: @foreach($items as $item).in instead of as.@for($i = 1; $i <= 3; $i++)
Number: {{ $i }}
@endfor@foreach($users as user)
{{ $user->name }}
@endforeach@foreach($users as $user).@endforeach. So only missing $ is the error.@if(count($products) > 0) which correctly and explicitly checks if products exist before looping.@if($products), which works via implicit boolean conversion (empty arrays are falsy) but is less explicit and readable than count > 0.Pass the test and this pattern moves unknown