MasterPHP.in
Try Compiler →
Laravel Tutorial

Laravel Blade Control Structures: @if, @foreach and @forelse


In the last lesson you built an invoice detail page that prints values with {{ }}. Now the owner wants the invoice list page. It must show every invoice, one after another. Each invoice needs a badge that says Paid, Pending or Overdue. And when there are no invoices yet, the page should show a friendly message instead of a blank space.

Printing values is not enough for this. The page must make decisions, such as which badge to show, and it must repeat a block of HTML for every invoice. In plain PHP, this means filling your HTML with <?php ... ?> tags again.

Blade solves this with directives, which are short commands that start with @. In this lesson you will learn the directives for conditions and loops: @if, @foreach and @forelse, along with the helpful $loop variable.

 

Why Echo Is Not Enough

Here is a status badge written in plain PHP:

<?php if ($invoice['status'] === 'paid'): ?>
    <span>Paid</span>
<?php else: ?>
    <span>Pending</span>
<?php endif; ?>

It works, but the PHP tags break up the HTML and make the file hard to read. This is the same badge in Blade:

@if ($invoice['status'] === 'paid')
    <span>Paid</span>
@else
    <span>Pending</span>
@endif

Blade directives are converted to the same plain PHP behind the scenes, as you saw in the Blade Basics lesson. They are only a cleaner way of writing it, so everything you know about PHP conditions and loops still applies.

 

Setting Up the Invoice List

For the examples in this lesson, make sure each invoice in your InvoiceService has a status key. Here is how one entry looks:

1001 => [
    'client' => 'Sharma Traders',
    'amount' => 12500,
    'gst'    => 2250,
    'total'  => 14750,
    'status' => 'paid',
],

Add two more entries with the statuses pending and overdue. Then change the index() method of InvoiceController so that it returns a view instead of the test array from the Request lesson:

public function index()
{
    return view('invoices.index', [
        'invoices' => $this->invoiceService->all(),
    ]);
}

Create the file resources/views/invoices/index.blade.php. You will fill it in step by step.

 

Conditions with @if

The @if directive shows a block of HTML only when a condition is true. The condition inside the brackets is ordinary PHP.

 

@if, @elseif and @else

Use @elseif and @else for more than two outcomes. Every @if must be closed with @endif:

@if ($invoice['status'] === 'paid')
    <span>Paid</span>
@elseif ($invoice['status'] === 'overdue')
    <span>Overdue</span>
@else
    <span>Pending</span>
@endif

 

Writing Conditions

You can use every PHP comparison and logical operator you already know:

@if ($invoice['total'] > 50000 && $invoice['status'] !== 'paid')
    <p>High value invoice. Follow up soon.</p>
@endif

@if (count($invoices) > 0)
    <p>You have invoices.</p>
@endif

@if (session('status'))
    <p>{{ session('status') }}</p>
@endif

The last example is the flash message check from the Redirects lesson. Laravel also has a shorter directive for it. Inside @session, the message is available in a variable called $value:

@session('status')
    <p>{{ $value }}</p>
@endsession

 

@unless

The @unless directive is the opposite of @if. It runs the block when the condition is false. It reads well for simple cases, such as showing a reminder button only for invoices that are not paid:

@unless ($invoice['status'] === 'paid')
    <a href="#">Send reminder</a>
@endunless

 

@isset and @empty

The @isset directive checks that a variable or key exists and is not null. The @empty directive checks that a value is empty. These are the Blade versions of the PHP functions isset() and empty():

@isset($invoice['note'])
    <p>Note: {{ $invoice['note'] }}</p>
@endisset

@empty($invoices)
    <p>No invoices yet.</p>
@endempty

PHP treats an empty array, an empty string, 0, "0", false and null as empty. If a value of 0 is valid for you, use an @if with a clear comparison instead. For a simple default value, the ?? operator from the last lesson is often shorter than @isset.

 

@switch

When one value can have many exact matches, @switch is an option:

@switch($invoice['status'])
    @case('paid')
        Paid
        @break

    @case('overdue')
        Overdue
        @break

    @default
        Pending
@endswitch

For two or three outcomes, @if and @elseif are usually easier to read. Use @switch only when it really makes the file clearer.

 

Loops with @foreach

The @foreach directive repeats a block once for each item in an array. It works exactly like the PHP loop of the same name, with @endforeach to close it.

 

Looping over Invoices

Your service returns an array where each key is the invoice number. Reading both the key and the value looks like this:

<ul>
    @foreach ($invoices as $number => $invoice)
        <li>Invoice {{ $number }}: {{ $invoice['client'] }}</li>
    @endforeach
</ul>

For three invoices, the browser receives three <li> lines. You write the HTML once, and Blade repeats it. Later, when your invoices come from the database as a list of models, the same loop works with them too.

 

The $loop Variable

Inside every @foreach, Laravel gives you a special variable called $loop. It knows where you are in the loop:

  • $loop->index is the position, starting at 0
  • $loop->iteration is the position, starting at 1
  • $loop->first is true on the first round
  • $loop->last is true on the last round
  • $loop->count is the total number of items
  • $loop->remaining is how many rounds are left
  • $loop->even and $loop->odd tell you if the round is even or odd

The most common use is a serial number. You can also treat the last item differently:

@foreach ($invoices as $number => $invoice)
    <li>
        {{ $loop->iteration }}. {{ $invoice['client'] }}

        @if ($loop->last)
            (last invoice)
        @endif
    </li>
@endforeach

The $loop->odd and $loop->even values are useful for striped rows once you add Tailwind CSS to your pages in a later lesson.

 

@continue and @break

Use @continue to skip the current item, and @break to stop the loop completely. Both accept a condition in brackets:

@foreach ($invoices as $number => $invoice)
    @continue($invoice['status'] === 'cancelled')

    <li>{{ $invoice['client'] }}</li>
@endforeach

You can also use @break($loop->iteration > 10) to stop after ten rows. But do not use it to limit a long list. Loading all the data and then hiding most of it wastes time. The right way is to fetch only what you need, and you will learn that in the Pagination lesson.

 

Nested Loops

You can place a loop inside another loop. Imagine each invoice has an items list:

@foreach ($invoices as $invoice)
    <h3>{{ $invoice['client'] }}</h3>

    <ul>
        @foreach ($invoice['items'] as $item)
            <li>{{ $loop->iteration }}. {{ $item['name'] }} x {{ $item['qty'] }}</li>
        @endforeach
    </ul>
@endforeach

Inside the inner loop, $loop describes the inner one. To reach the outer loop, use $loop->parent, for example $loop->parent->iteration.

 

Handling Empty Lists with @forelse

What happens to the list page when there are no invoices at all? The @foreach runs zero times, and the page shows nothing. The user cannot tell whether the page is broken or empty.

A common fix is to wrap the loop in an @if:

@if (count($invoices) > 0)
    @foreach ($invoices as $number => $invoice)
        <li>{{ $invoice['client'] }}</li>
    @endforeach
@else
    <p>No invoices yet.</p>
@endif

It works, but Blade has a directive made for exactly this case. @forelse loops over the items, and runs the @empty part if there are none:

@forelse ($invoices as $number => $invoice)
    <li>{{ $invoice['client'] }}</li>
@empty
    <li>No invoices yet. Create your first invoice.</li>
@endforelse

It is shorter, and it is the best choice for any list that may be empty. This @empty is part of @forelse, and it is not the same as the @empty($invoices) directive from earlier.

 

@for and @while

Blade also has @for and @while, which behave like their PHP versions. You will use them far less than @foreach, because most of your data comes as a list:

@for ($i = 1; $i <= 3; $i++)
    <p>Copy {{ $i }} of 3</p>
@endfor

Be careful with @while. If the condition never becomes false, the page loops forever. When you have an array or a list, choose @foreach or @forelse.

 

Putting It Together: The Invoice List Page

Here is the complete resources/views/invoices/index.blade.php, combining the flash message, a loop with an empty state, the $loop serial number and the status badge. It also uses route() from the Named Routes lesson, and Number::currency() from the last lesson:

@use('Illuminate\Support\Number')

<h1>Invoices</h1>

@session('status')
    <p>{{ $value }}</p>
@endsession

<p>Total invoices: {{ count($invoices) }}</p>

<ul>
    @forelse ($invoices as $number => $invoice)
        <li>
            {{ $loop->iteration }}.
            <a href="{{ route('invoices.show', $number) }}">Invoice {{ $number }}</a>
            for {{ $invoice['client'] }},
            {{ Number::currency($invoice['total'], in: 'INR', locale: 'en_IN', precision: 0) }}

            @if ($invoice['status'] === 'paid')
                <strong>Paid</strong>
            @elseif ($invoice['status'] === 'overdue')
                <strong>Overdue</strong>
            @else
                <strong>Pending</strong>
            @endif
        </li>
    @empty
        <li>No invoices yet. Create your first invoice.</li>
    @endforelse
</ul>

Open http://localhost:8000/invoices and you will see something like this:

Invoices
Total invoices: 3

1. Invoice 1001 for Sharma Traders, ₹14,750 Paid
2. Invoice 1002 for Gupta Electricals, ₹29,500 Pending
3. Invoice 1003 for Iyer & Sons, ₹8,850 Overdue

To test the empty state, temporarily return an empty array from the controller with 'invoices' => []. You will see the message, and the Total invoices line will show 0. Put the real data back when you are done.

 

Common Mistakes

 

Mistake 1: Forgetting the Closing Directive

@if ($invoice['status'] === 'paid')
    <span>Paid</span>

Every @if, @foreach, @forelse, @unless and @switch needs its own closing directive. If you forget it, the converted PHP file is broken, and Laravel shows:

ParseError: syntax error, unexpected end of file, expecting "elseif" or "else" or "endif"

For a loop, the message mentions the loop ending instead. Check that every opening directive has a matching end.

 

Mistake 2: Looping over null

@foreach ($invoices as $invoice)

If the controller forgets to send $invoices, you get Undefined variable $invoices. If it sends null, PHP shows:

ErrorException: foreach() argument must be of type array|object, null given

Always send an array, even an empty one, and use @forelse to handle the empty case.

 

Mistake 3: Using = Instead of ===

@if ($invoice['status'] = 'paid')
    <span>Paid</span>
@endif

A single equals sign assigns a value. It does not compare, so the condition is always true, and it also overwrites the real status. There is no error message. Use === to compare.

 

Mistake 4: Using $loop Outside a Loop

<p>Row {{ $loop->iteration }}</p>

The $loop variable exists only inside @foreach and @forelse. Anywhere else, you get:

ErrorException: Undefined variable $loop

 

Mistake 5: Running Queries Inside a Loop

@foreach ($invoices as $invoice)
    {{ \App\Models\Client::find($invoice->client_id)->name }}
@endforeach

This asks the database for one client on every round. A list of 100 invoices causes 100 extra queries, and the page becomes slow. This is called the N+1 problem, and you will learn the fix in the Eager Loading lesson. For now, remember that views should only display data that the controller has already prepared.

 

Mistake 6: Too Much Logic in the Template

@if ($invoice['status'] === 'paid' && $invoice['total'] > 50000 && $invoice['gst'] > 0 && now()->diffInDays($invoice['paid_on']) < 30)

A long condition is hard to read and hard to test. Work it out in the controller or service, give it a clear name like $isRecentLargePayment, and write @if ($isRecentLargePayment) in the view. Later, Eloquent accessors will give you a clean place for this kind of logic.

 

Quick Summary

  • Blade directives start with @, and are converted to plain PHP behind the scenes.
  • Every opening directive, such as @if or @foreach, needs a closing one, such as @endif or @endforeach.
  • @if, @elseif and @else show content based on a PHP condition. Compare with ===, not =.
  • @unless runs when a condition is false, @isset checks that a value exists, and @empty checks that it is empty.
  • @switch is for one value with many exact matches, but @if is often clearer.
  • @foreach ($invoices as $number => $invoice) repeats a block for every item.
  • Inside a loop, $loop->iteration, $loop->first, $loop->last and $loop->count describe the current position.
  • @continue skips an item and @break stops the loop. Limit long lists with pagination, not @break.
  • @forelse with @empty is the best way to loop over a list that may be empty.
  • @for and @while exist, but you will use @foreach most of the time.
  • Keep queries and heavy logic out of views. Prepare data in the controller or service.

 

What’s Next

Look at the two pages you have built, the invoice list and the invoice detail. Each one repeats its own heading, and neither has a proper <html> structure, a navigation bar or a footer. Copying all of that into every page will quickly become painful. In the next lesson, Layouts: @extends, @section & @yield, you will learn how to write the shared page structure once and let every page reuse it.

Frequently Asked Questions

The @empty directive checks whether one value is empty, such as an array or a string, and it has its own @endempty. The @forelse directive is a loop, and the @empty inside it is the part that runs when there is nothing to loop over. For lists that may be empty, @forelse is usually the better choice.
Use $loop->iteration, which starts counting at 1, or $loop->index, which starts counting at 0. The $loop variable is created by Laravel inside every foreach and forelse loop. It also gives you first, last, count and remaining.
The @isset directive only checks that a variable or key exists and is not null. The @if directive can test any condition you write, such as a comparison or a count. Use @isset for a quick existence check and @if when you need a real condition.
You can place an @if inside the class attribute, but it quickly becomes untidy. Blade has a class directive for this, called @class, which takes an array of class names and conditions. You will use it when you style the app with Tailwind CSS later in this chapter.
This almost always means a directive was opened but never closed. Check that every @if has an @endif, every @foreach has an @endforeach, and every @forelse has an @endforelse. Also check that each directive name is spelled correctly.

Share this tutorial