Blade Directives

Use @if, @foreach and other directives for logic in templates.

Syntax@foreach ($items as $item) ... @endforeach

Blade replaces messy PHP tags with clean @-directives:

  • @if / @else / @endif
  • @foreach / @endforeach
  • @forelse / @empty — loop with an empty fallback.

Example

Example · php
<ul>
@forelse ($posts as $post)
    <li>{{ $post->title }}</li>
@empty
    <li>No posts yet.</li>
@endforelse
</ul>

When to use it

  • An admin panel uses @can('delete-post', $post) in a Blade template to conditionally show the delete button only to users with the right policy permission.
  • A navigation bar uses @auth to show a logout link to signed-in users and @guest to show login/register links to visitors.
  • A multi-role dashboard uses @switch on the user's role to render a completely different sidebar for admins, editors, and viewers.

More examples

Authentication and authorisation directives

Demonstrates @auth, @guest, and @can — the three directives that gate UI elements based on authentication state and policy permissions.

Example · php
@auth
    <a href="{{ route('dashboard') }}">Dashboard</a>
    <form method="POST" action="{{ route('logout') }}">@csrf
        <button>Logout</button>
    </form>
@endauth

@guest
    <a href="{{ route('login') }}">Login</a>
    <a href="{{ route('register') }}">Register</a>
@endguest

@can('edit-post', $post)
    <a href="{{ route('posts.edit', $post) }}">Edit</a>
@endcan

Switch, unless, and isset directives

Shows @switch for multi-branch role checks, @isset for optional variables, and @unless as the inverse of @if.

Example · php
@switch($user->role)
    @case('admin')
        @include('partials.admin-sidebar')
        @break
    @case('editor')
        @include('partials.editor-sidebar')
        @break
    @default
        @include('partials.viewer-sidebar')
@endswitch

@isset($title)
    <title>{{ $title }}</title>
@endisset

@unless($user->isPremium())
    <div class="upgrade-banner">Upgrade to Pro</div>
@endunless

Loop helpers: $loop variable

Inside @foreach, the $loop magic variable exposes first, last, index, iteration, and remaining properties for styling and logic.

Example · php
@foreach ($items as $item)
    @if ($loop->first)
        <li class="first">{{ $item->name }}</li>
    @elseif ($loop->last)
        <li class="last">{{ $item->name }}</li>
    @else
        <li>{{ $item->name }}</li>
    @endif

    {{-- $loop->index, $loop->iteration, $loop->remaining --}}
@endforeach

Discussion

  • Be the first to comment on this lesson.