Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 67 ยท Views and Blade

Blade Templates

Learn Blade, Laravel's template engine: echoing and escaping data, @if and @foreach, @forelse, the $loop variable, @php, @json and the danger of raw output.

A web page is HTML with some values and decisions mixed in: the user's name, a list of posts, a message that only shows when something went wrong. You could write that in plain PHP tags, as in PHP and HTML, but the result gets noisy fast. Blade is Laravel's template engine. It gives you short directives such as @if and @foreach, escapes output by default, and compiles every template to ordinary PHP, so there is almost no runtime cost.

Blade files live in resources/views and end in .blade.php. You return one from a route or controller with the view() helper, passing an array of data. The file resources/views/posts/index.blade.php is addressed as posts.index:

PHP
<?php

// routes/web.php
use Illuminate\Support\Facades\Route;

Route::get('/posts', function () {
    return view('posts.index', [
        'title' => 'Latest posts',
        'posts' => [['title' => 'Hello'], ['title' => 'Blade rocks']],
    ]);
});

// Shortcut when a route only shows a view:
Route::view('/about', 'about', ['team' => 'Ada and Grace']);

Laravel code cannot run on this site, so the real framework snippets are read-only. The runnable examples build a tiny stand-in for Blade's compiler in plain PHP so you can see what happens to a template behind the scenes.

Echoing data and escaping

Double curly braces print a value:

BLADE
<h1>{{ $title }}</h1>
<p>Hello, {{ $user->name }}!</p>
<p>{{ strtoupper($title) }}</p>
<p>Total: {{ number_format($total, 2) }}</p>

Anything inside the braces is a PHP expression. Blade passes the result through e(), Laravel's wrapper around htmlspecialchars, so <, >, &, " and ' become entities. This is your main defense against cross-site scripting (XSS), covered in XSS and output escaping.

To print without escaping, use {!! ... !!}. Do that only for HTML that you produced and trust, such as the output of a Markdown renderer you configured, never for anything a visitor typed.

BLADE
{{-- This is a Blade comment: it never reaches the browser --}}
{!! $trustedHtml !!}

If a JavaScript framework on the same page also uses curly braces, prefix them with @ so Blade leaves them alone, or wrap a block in @verbatim ... @endverbatim:

BLADE
<p>Hello, @{{ name }}</p>

What Blade does to a template

Blade turns your file into PHP once, stores the result in storage/framework/views, and reuses it until the template changes. In production you can precompile everything with php artisan view:cache and clear the compiled files with php artisan view:clear. The performance lesson shows where this fits.

flowchart LR
    T["posts/index.blade.php"] --> C["Blade compiler"]
    C --> P["Compiled PHP file<br/>in storage/framework/views"]
    D["Data array"] --> R["PHP runs the compiled file"]
    P --> R
    R --> H["HTML string"]

Compilation happens once per template change; every request after that just runs plain PHP.

The next example is a stand-in compiler with a handful of directives. It is not Blade's real code (which is far more thorough), but the idea is the same: regular expressions turn directives into PHP tags, and the result is run with your data. The example prints the compiled PHP and then the rendered output.

PHP A mini Blade compiler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that {{ $title }} became <?php echo e($title); ?>. That one line is the whole security story: unless you say otherwise, the value goes through e().

Conditions and loops

Blade's directives map directly onto PHP's control structures. Each opening directive has a matching @end...:

BLADE
@if (count($orders) > 1)
    <p>You have several orders.</p>
@elseif (count($orders) === 1)
    <p>You have one order.</p>
@else
    <p>No orders yet.</p>
@endif

@unless ($user->isAdmin())
    <p>Admin tools are hidden.</p>
@endunless

@isset($banner) <p>{{ $banner }}</p> @endisset
@empty($cart) <p>Your cart is empty.</p> @endempty

Loops come in four flavors, and @forelse is the one that saves you an extra if:

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

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

@for ($i = 1; $i <= 3; $i++) <span>{{ $i }}</span> @endfor
@while ($row = $rows->next()) ... @endwhile

Inside a loop you can use @continue and @break, optionally with a condition: @continue($post->isHidden()).

A few conditional directives are shortcuts you will use all the time:

BLADE
@auth <a href="/dashboard">Dashboard</a> @endauth
@guest <a href="/login">Log in</a> @endguest
@production <script src="/analytics.js"></script> @endproduction
@env('local') <p>Debug banner</p> @endenv

For HTML attributes there are helpers that print the attribute only when a condition holds:

BLADE
<input type="checkbox" @checked(old('terms')) @disabled($locked)>
<option value="draft" @selected($status === 'draft')>Draft</option>
<div @class(['card', 'card-active' => $active, 'card-muted' => ! $active])>

The $loop variable

Inside a @foreach or @forelse, Laravel gives you a $loop object with information about the current iteration:

Property Meaning
$loop->index Zero-based index of the current iteration
$loop->iteration One-based counter
$loop->first, $loop->last True on the first or last iteration
$loop->even, $loop->odd Parity of the iteration
$loop->count, $loop->remaining Total items and how many are left
$loop->depth, $loop->parent Nesting level and the outer loop's $loop
BLADE
@foreach ($steps as $step)
    <li @class(['font-bold' => $loop->first])>
        {{ $loop->iteration }} of {{ $loop->count }}: {{ $step }}
    </li>
@endforeach

Raw PHP and variables

When a directive is not enough, @php ... @endphp runs a block of PHP. Keep it rare: logic belongs in controllers, models and view components, not in templates.

BLADE
@php
    $total = collect($items)->sum('price');
@endphp
<p>Total: {{ $total }}</p>

To hand PHP data to JavaScript, use Js::from() or @json:

BLADE
<script>
    const cart = {{ Js::from($cart) }};
</script>

Js::from() encodes with flags that are safe inside a <script> element and inside HTML attributes. The plain @json($cart) directive is a thin json_encode call, so use it only for data you control and prefer Js::from() otherwise.

Why raw output is dangerous

The second example shows what the same user input does with {{ }} and {!! !!}. The comment below came from a visitor.

PHP Escaped versus raw output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With {!! !!} the browser would see a real <img> tag whose onerror handler runs the visitor's JavaScript on your page. With {{ }} the browser sees harmless text. Escaping is applied at the moment of output, which is the right place: store the visitor's text as typed, and escape for the context (HTML, attribute, JavaScript) when you print.

Echoing in practice

  • A variable that might not exist needs a default: {{ $name ?? 'Guest' }}.
  • Blade echoes are statements for HTML. Don't build HTML strings in PHP to print with {!! !!}: use components instead (see Layouts, Components and Slots).
  • Keep expressions short. If a line gets long, compute the value in the controller or a view model.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does {{ $name }} do with the value?

    Blade compiles {{ }} to an echo wrapped in e(), which converts special characters to HTML entities.
  2. 2. When is {!! $html !!} acceptable?

    Raw output skips escaping, so it must be limited to markup your own code generated. User-supplied text printed raw is an XSS hole.
  3. 3. Which directive avoids a separate @if when a list may be empty?

    @forelse loops over the items and runs the @empty branch when there are none.
  4. 4. What is $loop->iteration inside a @foreach?

    iteration starts at 1, while index starts at 0. count holds the total and remaining the items left.
  5. 5. Where does Blade keep compiled templates?

    Compiled PHP files are written to storage/framework/views and reused until the template changes. view:clear removes them.

Summary

  • Blade templates are .blade.php files in resources/views, rendered with view('folder.name', $data).
  • {{ }} escapes through e(); {!! !!} prints raw and is safe only for trusted HTML.
  • Directives such as @if, @foreach, @forelse, @auth and @class map to PHP control structures and helpers.
  • $loop exposes index, iteration, first, last, count and more inside loops.
  • Use Js::from() to pass data to JavaScript, and keep @php blocks rare.
  • Templates compile to PHP once and are cached in storage/framework/views.

Next: Layouts, Components and Slots