In Laravel's Blade templating engine, you can use loops to iterate over arrays, collections, or ranges. Blade provides directives for various types of loops. Here are some common loop directives:
The @foreach
directive is used to iterate over arrays or collections:
@foreach ($items as $item)
{{ $item }}
@endforeach
You can also access the current index using @foreach ($items as $index => $item)
, where $index
represents the index of the current item.
The @for
directive is used for a traditional loop structure:
@for ($i = 0; $i < 5; $i++)
{{ $i }}
@endfor
The @while
directive is used to execute a block of code repeatedly as long as a condition is true:
@php
$i = 0;
@endphp
@while ($i < 5)
{{ $i }}
@php
$i++;
@endphp
@endwhile
Blade also provides loop control directives:
@continue
to skip the current iteration and continue with the next one.@break
to stop the loop execution.@foreach ($items as $item)
@if ($item === 'skip')
@continue
@endif
{{ $item }}
@if ($item === 'stop')
@break
@endif
@endforeach
Within loops, Blade automatically provides loop variables such as $loop->index
, $loop->iteration
, $loop->first
, $loop->last
, etc., which you can use to get information about the current loop iteration.
@foreach ($items as $item)
{{ $loop->index }}: {{ $item }}
@endforeach
You can also nest loops within each other:
@foreach ($users as $user)
@foreach ($user->posts as $post)
{{ $user->name }} - {{ $post->title }}
@endforeach
@endforeach
These are some of the common loop directives and techniques in Laravel's Blade templating engine. They provide powerful tools for iterating over data and displaying dynamic content in your views.