LOOPING THROUGH DATA IN BLADE

Jun 23, 2025 Copy Link

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.

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE