Laravel Blade Loops


In Laravel Blade, loops allow you to iterate over arrays or collections and display content dynamically. Blade provides several directives for handling loops, including @for, @foreach, @forelse, and @while. Here’s a detailed overview of how to use these looping directives:

1. @foreach Directive

Description: The @foreach directive is used to loop through each item in an array or collection.

Basic Syntax:

@foreach ($items as $item) // HTML or Blade syntax for each $item @endforeach

Example:

Assume $users is an array of user objects:

@foreach ($users as $user) <p>{{ $user->name }}</p> @endforeach

This will output the name of each user in the $users array.

2. @forelse Directive

Description: The @forelse directive is similar to @foreach, but it also provides a way to handle empty arrays or collections with an @empty block.

Basic Syntax:

@forelse ($items as $item) // HTML or Blade syntax for each $item @empty // HTML or Blade syntax when $items is empty @endforelse

Example:

@forelse ($users as $user) <p>{{ $user->name }}</p> @empty <p>No users found.</p> @endforelse

If $users is empty, it will display "No users found."

3. @for Directive

Description: The @for directive is used for a traditional for loop. It’s useful when you need to loop a specific number of times.

Basic Syntax:

@for ($i = 0; $i < 10; $i++) <p>Item {{ $i }}</p> @endfor

This will output a list of items from 0 to 9.

4. @while Directive

Description: The @while directive is used for a while loop, which continues to loop as long as the condition is true.

Basic Syntax:

@while ($i < 10) <p>Item {{ $i }}</p> @php $i++; @endphp @endwhile

This will output a list of items as long as $i is less than 10. Note that you need to manually increment $i inside the loop.

5. Loop Variables

Blade provides some useful loop variables within loops:

  • $loop: An instance of Illuminate\View\Concerns\ManagesLoops. It provides information about the current iteration, including:
    • $loop->index: The current iteration (starting from 0).
    • $loop->iteration: The current iteration (starting from 1).
    • $loop->remaining: The number of iterations left.
    • $loop->count: The total number of items.
    • $loop->first: True if the current iteration is the first.
    • $loop->last: True if the current iteration is the last.

Example:

@foreach ($users as $user) <p> @if ($loop->first) This is the first user. @elseif ($loop->last) This is the last user. @endif {{ $user->name }} </p> @endforeach

Summary

Laravel Blade’s looping directives (@foreach, @forelse, @for, and @while) make it easy to iterate over arrays or collections and display content dynamically. They offer a variety of options for different looping needs and include useful loop variables for managing the iteration process.