Laravel Blade offers several clean and expressive ways to loop through data.
1. Basic Loop with @foreach
The most common way to iterate over a collection is using the `@foreach` directive:
<table class="table">
@foreach ($posts as $post)
<tr>
<td>{{ $post->title }}</td>
<td>{{ $post->body }}</td>
</tr>
@endforeach
</table>
You can control loop execution using the `@break` and `@continue` directives:
<table class="table">
@foreach ($posts as $post)
@if ($post->user->is_blocked)
@break
@endif
@if ($post->user_id == user()->id())
@continue
@endif
<tr>
<td>{{ $post->title }}</td>
<td>{{ $post->body }}</td>
</tr>
@endforeach
</table>
Laravel also provides a more concise version of `@break` and `@continue` by passing the condition directly:
<table class="table">
@foreach ($posts as $post)
@break($post->user->is_blocked)
@continue($post->user_id == user()->id())
...
@endforeach
</table>
2. Handling Empty Collections with @forelse
If you want to display a fallback message when the collection is empty, use the `@forelse` directive:
<table class="table">
@forelse ($posts as $post)
<tr>
<td>{{ $post->title }}</td>
<td>{{ $post->body }}</td>
</tr>
@empty
<tr>
<td colspan="2">No posts found</td>
</tr>
@endforelse
</table>
Alternatively, you can use the @each directive, which provides a more concise way to loop through data and render rows. It accepts four parameters:
1. View: The view file that contains the HTML for a single row.
2. Variable: The name of the variable for each item in the loop.
3. Data: The collection or array of data to loop through.
4. Empty View: The view that will be displayed if the data is empty.
@each('posts.row', $posts, 'post', 'posts.empty')
Laravel provides a way to gain more control over your iterations using the $loop variable.