Control structures help you decide what to show or repeat in your web pages. They make your templates smart and dynamic.
Show a message only if a user is logged in.
List all items in a shopping cart.
Repeat a block of HTML a fixed number of times.
Display different content based on a condition.
Syntax
Laravel
@if (condition)
// code to show if true
@elseif (another_condition)
// code to show if elseif true
@else
// code to show if all false
@endif
@foreach ($items as $item)
// code to repeat for each item
@endforeach
@for ($i = 0; $i < 5; $i++)
// code to repeat 5 times
@endfor
Use @if to check conditions and show content accordingly.
@foreach loops over each item in a list.
@for repeats code a set number of times.
Examples
Shows a message depending on whether the user is an admin.
D. @if($products)
@foreach($products as $product)
{{ $product->name }}
@endforeach
@endif
Solution
Step 1: Check condition to display list
@if(count($products) > 0)
@foreach($products as $product)
{{ $product->name }}
@endforeach
@endif uses @if(count($products) > 0) which correctly and explicitly checks if products exist before looping.
Step 2: Analyze other options
B places the check inside the loop, which is redundant since @foreach skips empty arrays. C uses manual @for with array indexing, which is error-prone (e.g., for associative arrays) and less idiomatic than @foreach. D uses @if($products), which works via implicit boolean conversion (empty arrays are falsy) but is less explicit and readable than count > 0.
Final Answer:
@if(count($products) > 0) followed by @foreach -> Option A
Quick Check:
Check count > 0 before @foreach [OK]
Hint: Use count() > 0 to check non-empty arrays before loops [OK]
Common Mistakes:
Using implicit @if($products) instead of explicit count > 0
Placing condition inside loop unnecessarily
Using @for with inner @if redundantly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.