Laravel Blade Directives

Laravel Blade Directives

Blade directives are shorthand for common PHP control structures, making templates cleaner and easier to read.

1 - Conditionals

@if ($user->isAdmin())
    <span>Admin</span>
@elseif ($user->isModerator())
    <span>Moderator</span>
@else
    <span>Member</span>
@endif

@unless ($user->isVerified())
    <p>Please verify your email.</p>
@endunless

2 - Loops

@foreach ($posts as $post)
    <h2>{{ $post->title }}</h2>
@endforeach

@forelse ($comments as $comment)
    <p>{{ $comment->body }}</p>
@empty
    <p>No comments yet.</p>
@endforelse

@for ($i = 0; $i < 3; $i++)
    <p>Item {{ $i }}</p>
@endfor

3 - The $loop Variable

@foreach ($items as $item)
    @if ($loop->first) <ul> @endif
    <li>{{ $loop->iteration }}. {{ $item->name }}</li>
    @if ($loop->last) </ul> @endif
@endforeach

// Useful $loop properties:
// $loop->index     — zero-based index
// $loop->iteration — one-based count
// $loop->first / $loop->last
// $loop->count — total items

4 - Authentication Directives

@auth
    <a href="{{ route('dashboard') }}">Dashboard</a>
@endauth

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

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