All Blade Templates lessons

Core Blade directives

4 min read

Blade compiles to PHP, so directives are just sugar for common patterns.

Conditionals

@if($user->isAdmin())
    <span class="badge">Admin</span>
@elseif($user->is_active)
    <span>Active</span>
@else
    <span>Pending</span>
@endif

Loops

@foreach($posts as $post)
    <article>{{ $post->title }}</article>
@empty
    <p>No posts yet.</p>
@endforeach

@empty runs when the collection is empty — saves an extra @if(count() == 0).

Forms & auth

<form method="POST" action="/posts">
    @csrf                           {{-- adds hidden _token --}}
    @method('PUT')                  {{-- spoofs PUT (HTML only knows GET/POST) --}}
    <input name="title">
    <button>Save</button>
</form>

@auth
    Welcome, {{ auth()->user()->name }}!
@else
    <a href="{{ route('login') }}">Sign in</a>
@endauth

Escaping

{{ $x }} HTML-escapes automatically — safe by default. {!! $x !!} renders raw HTML and is XSS-prone; only use it when you actually mean it (e.g. trusted Markdown output).