Using @foreach Loops in Laravel Blade (Plus Common Questions)

In Laravel Blade templates, you can use built-in syntax to loop over collections and show their content in various ways.

This blog post will guide you through an example in which we’ll show all users found in the database and display them using a @foreach loop.

Following that, I will also address frequently asked questions regarding the foreach loop in Blade, such as handling an empty collection, using a loop counter, exiting a loop prematurely, working with key/value pairs, and identifying odd or even rows.

Let’s get started!

Step 1: Create a Controller

First, let’s create a controller that will handle our data and pass it to the view. You can use any existing model, but for this example, we’ll use the default User model.

php artisan make:controller UserController

Add Code to the Controller:

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

class UserController extends Controller
{
    public function index()
    {
        return view('users', [
            'users' => User::all()
        ]);
    }
}

Step 2: Define a Route

Next, define a route in the routes/web.php file that will link to the controller’s method. We’ll use the index method in this case.

routes/web.php
use App\Http\Controllers\UserController;

Route::get('/users', [UserController::class, 'index']);

Step 3: Create a Blade View

Now, create a Blade view to display the data using the foreach loop. Create a file named users.blade.php in the resources/views directory.

resources/views/user-index.blade.php
<h1>User List</h1>
<ul>
    @foreach($users as $user)
        <li>{{ $user->name }}</li>
    @endforeach
</ul>

That’s it! Laravel makes it very easy to loop over collections like this and display them. Read on to learn about what other cases we can build using foreach in blade.

Frequently Asked Questions

How to Access Loop Count in a @foreach in Blade?

To access the loop count in a foreach loop in Laravel Blade, you can use the loop variable’s “iteration” property for example: {{ $loop->iteration }}.

Here’s a full example showing a table containing users with a counter in each row:

views/fruits.blade.php
<table>
    <tr>
        <th>Loop Count</th>
        <th>Fruit</th>
    </tr>
    @foreach ($users as $user)
        <tr>
            <td>{{ $loop->iteration }}</td>
            <td>{{ ucfirst($user) }}</td>
        </tr>
    @endforeach
</table>

How to Access Key and Value in a @foreach in Blade?

To access key-value pairs in a foreach loop in Laravel Blade, you can use the syntax @foreach ($array as $key => $value).

Here’s some example code that shows fruits and their prices based on an associative array:

app/Http/Controllers/FruitController.php
<?php

namespace App\Http\Controllers;

class FruitController extends Controller
{
    public function index()
    {
        $fruits = [
            'apple' => 0.99,
            'banana' => 0.49,
            'orange' => 0.79,
            'grape' => 1.29,
        ];

        return view('fruits', ['fruits' => $fruits]);
    }
}
resources/views/fruits.blade.php
@foreach ($fruits as $fruit => $price)
    <p>The price of {{ ucfirst($fruit) }} is ${{ number_format($price, 2) }}.</p>
@endforeach

How to Check if Collection is Empty in a Blade Foreach Loop?

When using a foreach in blade, the shortest way to check if a collection is empty is by using @forelse together with the @empty directive. Alternatively, you can also use: @if (empty($collection)) .. @endif.

Here’s an example of how you can do it:

resources/views/products.blade.php
<table>
    <thead>
        <tr>
            <th>Product ID</th>
            <th>Product Name</th>
        </tr>
    </thead>
    <tbody>
        @forelse ($products as $product)
            <tr>
                <td>{{ $product->id }}</td>
                <td>{{ $product->name }}</td>
            </tr>
        @empty
            <tr>
                <td colspan="2">No products available</td>
            </tr>
        @endforelse
    </tbody>
</table>

In the example, the @forelse directive is used instead of @foreach. The @forelse directive is specifically designed for handling empty loops. If $products is empty, the code within @empty displays “No products available” in a row. For non-empty collections, the regular loop code will run and show the product details.

Alternatively, it can be useful to use a simple @if instead. For example, if you don’t want to show a table at all if there is no user found to show. For that case consider the following code:

resources/views/users.blade.php
@if (empty($users))
    <p>No users found</p>
@else
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($users as $user)
                <tr>
                    <td>{{ $user->name }}</td>
                    <td>{{ $user->email }}</td>
                </tr>
            @endforeach
        </tbody>
    </table>
@endif

How to Show Content Only for the First Item in a Blade loop?

To display specific content only for the first item in a Blade @foreach loop, you can use the loop variable’s “first” property by using the following code: @if ($loop->first)@endif.”

Here’s how you can achieve this:

resources/views/posts.blade.php
@foreach ($posts as $key => $post)
    @if ($loop->first)
        <!-- Special styling or content for the first post -->
        <div class="featured-post">
            <h2>{{ $post->title }}</h2>
            <p>{{ $post->excerpt }}</p>
            <span class="featured-label">Featured</span>
        </div>
    @else
        <!-- Regular styling or content for other posts -->
        <div class="normal-post">
            <h3>{{ $post->title }}</h3>
            <p>{{ $post->excerpt }}</p>
        </div>
    @endif
@endforeach

How to Check if Odd or Even Using a @foreach in Blade?

To format or style content differently based on whether the loop iteration is odd or even, you can use the $loop variable’s even and odd properties. Here’s an example:

resources/views/users.blade.php
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($users as $user)
            <tr class="{{ $loop->even ? 'even' : 'odd' }}">
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

Conclusion

Foreach loops in Laravel Blade are a fundamental tool for iterating data and displaying it within your views. You’ve learned to work with foreach loops while using key-value pairs, using loop counts, managing empty collections, customizing the appearance of the first item, and distinguishing odd and even iterations using the $loop variable.

Now go ahead and add foreach loops to your own projects and show some iterative data to your users. Happy coding!

References

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

One thought on “Using @foreach Loops in Laravel Blade (Plus Common Questions)

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts