0
0
LaravelHow-ToBeginner · 3 min read

How to Use @foreach in Blade Templates in Laravel

Use the @foreach directive in Blade to loop over arrays or collections. It starts with @foreach ($items as $item) and ends with @endforeach, letting you display each element inside the loop.
📐

Syntax

The @foreach directive loops over each item in a collection or array. You write @foreach ($collection as $item) to start the loop, then place the code to run for each item, and close it with @endforeach.

  • $collection: The array or collection you want to loop through.
  • $item: The variable representing the current element in the loop.
php
@foreach ($items as $item)
    <!-- Use $item here -->
@endforeach
💻

Example

This example shows how to loop through a list of fruits and display each one inside an unordered list.

blade
@php
$fruits = ['Apple', 'Banana', 'Cherry'];
@endphp

<ul>
@foreach ($fruits as $fruit)
    <li>{{ $fruit }}</li>
@endforeach
</ul>
Output
<ul> <li>Apple</li> <li>Banana</li> <li>Cherry</li> </ul>
⚠️

Common Pitfalls

Common mistakes include forgetting to close the loop with @endforeach, using the wrong variable name inside the loop, or trying to loop over a variable that is not an array or collection.

Also, avoid using PHP foreach syntax inside Blade templates; always use the Blade @foreach directive for clarity and consistency.

blade
@php
$items = ['One', 'Two', 'Three'];
@endphp

<!-- Wrong: missing @endforeach -->
<ul>
@foreach ($items as $item)
    <li>{{ $item }}</li>
<!-- Missing @endforeach here -->
</ul>

<!-- Correct -->
<ul>
@foreach ($items as $item)
    <li>{{ $item }}</li>
@endforeach
</ul>
📊

Quick Reference

  • @foreach ($array as $value): Start loop
  • @endforeach: End loop
  • Use {{ $value }} to display current item
  • Works with arrays and Laravel collections

Key Takeaways

Use @foreach to loop through arrays or collections in Blade templates.
Always close the loop with @endforeach to avoid errors.
Inside the loop, use the loop variable to access each item.
Avoid mixing PHP foreach syntax with Blade directives.
Ensure the variable you loop over is an array or collection to prevent errors.