Skip to main content
Blade Templates

Blade Templates

Blade is Laravel's template engine. It compiles templates to plain PHP and caches the result, so it stays fast while offering concise syntax for escaping, control flow, and reusable components.

Output and directives

<h1>{{ $post->title }}</h1>
<p>Published {{ $post->created_at->diffForHumans() }}</p>

@if ($post->isDraft())
    <span class="badge">Draft</span>
@elseif ($post->isScheduled())
    <span class="badge">Scheduled</span>
@else
    <span class="badge">Published</span>
@endif

{{ }} escapes HTML. {!! !!} renders raw HTML and should only receive content you have sanitized.

Loops

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

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

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

The $loop variable exposes index, iteration, first, last, and remaining inside a loop.

Conditional helpers

<div @class(['card', 'card--featured' => $post->featured])>...</div>

<button @disabled($post->isArchived())>Edit</button>

@unless ($post->published)
    <p>This post is hidden.</p>
@endunless

Components

Class-based components keep markup and small logic together.

php artisan make:component Alert
<!-- resources/views/components/alert.blade.php -->
@props(['type' => 'info'])

<div {{ $attributes->class(['alert', "alert-{$type}"]) }}>
    {{ $slot }}
</div>
<x-alert type="warning" class="mb-4">
    Your trial ends in three days.
</x-alert>

Stacks and push

Stacks let a child view add scripts or styles to a placeholder in the layout.

{{-- layout --}}
@stack('scripts')

{{-- child --}}
@push('scripts')
    <script></script>
@endpush

Authorization directives

@can('update', $post)
    <a>Edit</a>
@endcan

@guest
    <a>Sign in</a>
@endguest

Custom directives

If a pattern repeats across templates, register a directive in a service provider. Keep custom directives simple; complex logic belongs in a component class or view model.