Himanshu SharmaSoftware engineer
Let’s talk

Laravel · Lesson 10 of 40

Blade templates: output, conditions and loops

Render HTML pages with Blade views, print data safely with escaped double braces, use @if, @foreach and @forelse, and see the PHP Blade compiles to.

14 minViews, forms and validationUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonReturn views from controllers, pass data to them, and use Blade output, conditions and loops to build the Pagelane Books catalogue pages.

What you can do after this lesson

You will turn the JSON output of the earlier lessons into real HTML pages. After this lesson Pagelane Books has a home page, a catalogue and a book detail page, all written as Blade views.

Views and Blade

A view is a template. In Laravel views live in resources/views. A file named something.blade.php is processed by Blade, Laravel's template engine, which lets you write normal HTML plus a few short helpers. Blade adds no cost at run time: it compiles each template to plain PHP once, then reuses the compiled file.

From a controller you return a view, passing data as an array:

php
return view('books.index', ['books' => $books, 'search' => $search]);

The first argument is the view name, with dots as folder separators, so this loads resources/views/books/index.blade.php. Each array key becomes a variable inside the template. The home controller now returns view('home').

The controller keeps the sample list as objects, so templates can write $book->title. Here are the relevant parts of the updated BookController:

php
private function books(): Collection
{
    return collect(self::BOOKS)->map(fn (array $book) => (object) $book);
}

public function index(Request $request): View
{
    $search = (string) $request->query('search', '');

    $books = $this->books()->filter(
        fn (object $book) => $search === '' || str_contains(strtolower($book->title), strtolower($search)),
    );

    return view('books.index', ['books' => $books, 'search' => $search]);
}

public function show(int $id): View
{
    $book = $this->books()->firstWhere('id', $id);

    abort_if($book === null, 404);

    return view('books.show', ['book' => $book]);
}

(Each sample row now also has an id.) collect() wraps an array in a collection, an object with helpful methods such as map, filter and firstWhere. You will meet collections again with Eloquent.

Printing values safely

The core of Blade is the double-brace echo. Here is the book detail view, resources/views/books/show.blade.php:

blade
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{{ $book->title }} - {{ config('app.name') }}</title>
</head>
<body>
    <h1>{{ $book->title }}</h1>
    <p>by {{ $book->author }}</p>
    <p>Price: ${{ number_format($book->price_cents / 100, 2) }}</p>
    <p><a href="{{ route('books.index') }}">Back to all books</a></p>
</body>
</html>

Between the braces you can write any PHP expression: a variable, a function call, a ternary. Blade runs the result through PHP's htmlspecialchars equivalent, so < becomes &lt;. That escaping is your main defence against cross-site scripting (XSS), where an attacker's text is interpreted as HTML or script in someone else's browser. To see it, search for a tag:

bash
curl -s "localhost:8091/books?search=%3Cb%3Ex%3C/b%3E"
text
        <p>Results for "&lt;b&gt;x&lt;/b&gt;": 0</p>

The visitor typed <b>x</b> and the page shows it as harmless text. The unescaped form, a pair of braces with an exclamation mark inside each, prints raw HTML. Use it only for markup you wrote yourself and fully trust. A catalogue description typed by a user must never be printed that way.

To print literal curly braces (for a JavaScript framework, say), put @ before them or wrap the block in @verbatim. A Blade comment is written with braces and two dashes, and it does not reach the browser.

Conditions and loops

Directives begin with @. Here is the catalogue view, resources/views/books/index.blade.php:

blade
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Books - {{ config('app.name') }}</title>
</head>
<body>
    <h1>Books</h1>

    @if ($search !== '')
        <p>Results for "{{ $search }}": {{ $books->count() }}</p>
    @endif

    <ul>
        @forelse ($books as $book)
            <li>
                <a href="{{ route('books.show', $book->id) }}">{{ $book->title }}</a>
                by {{ $book->author }}
                (${{ number_format($book->price_cents / 100, 2) }})
                @if ($loop->first) <strong>first</strong> @endif
            </li>
        @empty
            <li>No books match your search.</li>
        @endforelse
    </ul>
</body>
</html>
  • @if, @elseif, @else, @endif work as in PHP; there are also @unless, @isset and @empty.
  • @foreach ($items as $item) loops; @for and @while also exist.
  • @forelse loops and falls back to @empty when there is nothing to show, which avoids a separate @if.
  • $loop is available in loops with first, last, index, iteration and count.

Request the page and you get the book rows, each linked by a route name:

text
<li>
    <a href="http://localhost:8091/books/1">The Quiet Harbour</a>
    by Mira Lindqvist
    ($14.50)
     <strong>first</strong>
</li>

The link host reflects the server you used. If you want to try Blade-like markup in a browser preview, the HTML viewer tool shows plain HTML; Blade itself needs Laravel to compile it.

What Blade compiles to

Blade is not magic. Look in storage/framework/views: each template becomes a PHP file such as this one for the detail page:

php
<title><?php echo e($book->title); ?> - <?php echo e(config('app.name')); ?></title>

e() is the escaping helper. Laravel rebuilds the file whenever the template changes, and php artisan view:clear removes all compiled files if you ever need a clean start.

Common mistakes

  • Using the unescaped echo with user text. Escape by default.
  • Putting queries or heavy logic in a template. Prepare data in the controller; the template only displays it.
  • Forgetting the end directive (@endif, @endforeach), which causes a confusing syntax error in the compiled file.
  • Wrong view name. books.index is a path; typing books/index or Books.index fails.
  • Expecting Blade to run in the browser. It runs on the server; the browser only ever receives HTML.

Exercise

On the catalogue page, show the number of books next to the heading (Books (3)) and add the words new in a <em> after the last book in the list, using $loop.

Show one possible answer
blade
<h1>Books ({{ $books->count() }})</h1>
...
@if ($loop->last) <em>new</em> @endif

The @if ($loop->last) goes inside the @forelse body, next to the $loop->first line. With three sample books the heading reads Books (3), and "new" appears after Salt and Signal. In the next lesson you remove the repeated page skeleton with layouts and components.

Key points

  • Views are files in resources/views ending in .blade.php; view('books.index', $data) renders resources/views/books/index.blade.php.
  • Double curly braces print a value and escape HTML, which protects against cross-site scripting; the unescaped form with exclamation marks must be used only for trusted HTML.
  • Directives such as @if, @foreach, @forelse and @empty start with @ and compile to plain PHP, so templates stay readable.
  • Inside a loop, the $loop variable tells you the index, whether you are on the first or last item and more.
  • Compiled templates are cached as PHP files in storage/framework/views and rebuilt automatically when the source changes.

Check yourself

1. What does {{ $title }} do if $title contains <b>Hi</b>?
2. Which file does view('books.show') render?
3. What is @forelse ... @empty for?
4. When is {!! $html !!} acceptable?

Free tools for this lesson