Laravel Blade Templates: Control Structures

If Statements

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
@unless (Auth::check())
    You are not signed in.
@endunless
@isset($records)
    // $records is defined and is not null...
@endisset

@empty($records)
    // $records is "empty"...
@endempty

Switch Statements

@switch($i)
    @case(1)
        First case...
        @break

    @case(2)
        Second case...
        @break

    @default
        Default case...
@endswitch

Loops

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

@while (true)
    <p>I'm looping forever.</p>
@endwhile
@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach
@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach

The Loop Variable

Provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop.

@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>This is user {{ $user->id }}</p>
@endforeach
@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach

Available inside of your loop.

  • $loop->index.
  • $loop->iteration.
  • $loop->remaining.
  • $loop->count.
  • $loop->first.
  • $loop->last.
  • $loop->depth.
  • $loop->parent.

Comments

{{-- This comment will not be present in the rendered HTML --}}

PHP

@php
    //
@endphp

You can use the Blade @php directive to execute a block of plain PHP within your template.

Laravel Blade Templates: Control Structures — Structure map

Clickable & Draggable!

Laravel Blade Templates: Control Structures — Related pages: