0
0
LaravelHow-ToBeginner · 3 min read

How to Use @while in Blade Templates in Laravel

In Laravel Blade templates, use the @while directive to create a loop that runs as long as a condition is true. Write @while(condition) followed by the loop content and close it with @endwhile.
📐

Syntax

The @while directive starts a loop that continues while the given condition is true. You must close it with @endwhile. Inside the loop, you can put any HTML or Blade code.

  • @while(condition): Begins the loop with a condition.
  • Loop content: Code or HTML to repeat.
  • @endwhile: Ends the loop.
blade
@while(condition)
    <!-- Loop content here -->
@endwhile
💻

Example

This example shows a simple counter that prints numbers from 1 to 5 using @while. It demonstrates how the loop runs while the condition is true and stops when it becomes false.

blade
@php
    $count = 1;
@endphp

@while($count <= 5)
    <p>Count is {{ $count }}</p>
    @php
        $count++;
    @endphp
@endwhile
Output
<p>Count is 1</p> <p>Count is 2</p> <p>Count is 3</p> <p>Count is 4</p> <p>Count is 5</p>
⚠️

Common Pitfalls

Common mistakes when using @while include:

  • Forgetting to update the condition variable inside the loop, causing an infinite loop.
  • Not closing the loop with @endwhile, which causes a Blade error.
  • Using complex logic inside the loop that is better handled in the controller.
blade
@php
    $count = 1;
@endphp

<!-- Wrong: Missing increment causes infinite loop -->
@while($count <= 3)
    <p>Count is {{ $count }}</p>
@endwhile

<!-- Right: Increment inside loop to avoid infinite loop -->
@php
    $count = 1;
@endphp
@while($count <= 3)
    <p>Count is {{ $count }}</p>
    @php $count++; @endphp
@endwhile
Output
<p>Count is 1</p> <p>Count is 2</p> <p>Count is 3</p>
📊

Quick Reference

Use @while(condition) to start a loop that runs while the condition is true. Always update the condition variable inside the loop to avoid infinite loops. Close the loop with @endwhile.

DirectiveDescription
@while(condition)Starts a loop that runs while the condition is true.
@endwhileEnds the @while loop.
Update condition variableMust be done inside the loop to prevent infinite loops.

Key Takeaways

Use @while(condition) and close with @endwhile to create loops in Blade.
Always update the condition variable inside the loop to avoid infinite loops.
Keep complex logic out of Blade loops; handle it in controllers when possible.
Forgetting @endwhile causes Blade errors.
Blade @while loops work like PHP while loops but are easier to write in templates.