How to Use @for Loop in Blade Templates in Laravel
In Laravel Blade templates, use the
@for directive to create a loop with a start, end, and optional step. It works like a standard for loop in PHP, allowing you to repeat HTML or Blade code multiple times easily.Syntax
The @for directive in Blade follows this pattern:
@for (initialization; condition; increment)starts the loop.- Place the code to repeat inside the loop.
@endforends the loop.
This is similar to PHP's for loop but designed for Blade templates.
php
@for ($i = 0; $i < 5; $i++) <!-- Loop content here --> @endfor
Example
This example shows how to print numbers 1 to 5 inside an unordered list using @for in a Blade template.
php
<ul> @for ($i = 1; $i <= 5; $i++) <li>Number {{ $i }}</li> @endfor </ul>
Output
<ul>
<li>Number 1</li>
<li>Number 2</li>
<li>Number 3</li>
<li>Number 4</li>
<li>Number 5</li>
</ul>
Common Pitfalls
Common mistakes when using @for include:
- Forgetting to close the loop with
@endfor, which causes syntax errors. - Using incorrect PHP syntax inside the parentheses, like missing semicolons.
- Trying to use variables not defined or accessible in the Blade view.
Always ensure your loop variables are properly initialized and the loop is closed.
php
@for ($i = 0; $i < 3; $i++) <p>Wrong syntax example</p> @endfor @for ($i = 0; $i < 3; $i++) <p>Correct syntax example</p> @endfor
Quick Reference
Use @for to loop with a counter in Blade templates. Remember:
- Start with
@for (init; condition; increment) - Put your repeated HTML or Blade code inside
- Close with
@endfor
This is perfect for fixed count loops or when you need the index.
Key Takeaways
Use @for in Blade to create loops with a start, condition, and increment like PHP for loops.
Always close your loop with @endfor to avoid syntax errors.
You can output variables inside the loop using Blade's {{ }} syntax.
Ensure your loop variables are defined and accessible in the Blade view.
Use @for for fixed count loops or when you need the loop index.