A plain PHP page tends to be a jumble. There's <?php foreach ($books as $book): ?> placed between <li> tags, <?= htmlspecialchars($book['title']) ?> every time you print data, and the same <header> copied into every file. If you forget one htmlspecialchars, someone else's script can get into the page.
Blade is Laravel's template engine, a tool that builds HTML from a template. A Blade template is a plain HTML file with blanks for data, plus a few short commands that start with @. The file ends in .blade.php, is stored in resources/views, and is called a view. Picture a letter form with dotted blanks: "To: ........". The paper is the same for everyone, only the blanks change. The Blade template is the paper, the controller's data fills the blanks, and @foreach is one line of blanks printed again for every book.
From the controller to the view
The controller hands data to a view with view():
public function index()
{
return view('books.index', [
'books' => [
['title' => 'The Rainbow Troops', 'stock' => 3],
['title' => 'This Earth of Mankind', 'stock' => 0],
['title' => 'Beauty Is a Wound', 'stock' => 2],
],
'note' => 'New <b>books</b> arrive Monday',
]);
}
'books.index'means the fileresources/views/books/index.blade.php. A dot marks a folder boundary (books.indexis the same asbooks/index), and the.blade.phpending isn't written.- The second argument, an array, is the data. Each key of the array becomes a variable in the view:
'books'becomes$books,'note'becomes$note. - The response is
200 OKwith HTML. In the exercise, your route is called, and the HTML page that Blade builds is printed underGET /profile → 200.
Showing data: {{ }} and {!! !!}
This is the content of resources/views/books/index.blade.php. The @extends, @section, @foreach and @if in it are covered in the next sections:
@extends('layouts.app')
@section('title', 'Book List')
@section('content')
<h1>Library Collection</h1>
<p>Note: {{ $note }}</p>
<ul>
@foreach ($books as $book)
<li>
{{ $book['title'] }}
@if ($book['stock'] > 0)
<b>Available</b>
@else
<i>All on loan</i>
@endif
</li>
@endforeach
</ul>
@endsection
Remember, $note from the controller holds New <b>books</b> arrive Monday. Guess first: on the page, does the word "books" come out bold or not?
The answer is no. {{ $note }} prints the variable after making its HTML characters safe. Making them safe means replacing them with codes that show as plain text: < becomes <, > becomes >, & becomes &, quotes become " and '. The browser shows the text New <b>books</b> arrive Monday as is, nothing in bold.
{!! $note !!} prints the content raw, without making it safe, so "books" comes out bold. If that content comes from a user and holds a <script>, the script runs in every visitor's browser. That's an XSS attack, covered in the Security track. The rule: always use {{ }}, except for HTML you wrote yourself.
Behind the scenes, Blade turns the template into plain PHP (this step is called compiling) and stores it in storage/framework/views. {{ $note }} becomes <?php echo e($note); ?>, and e() is a Laravel function that runs htmlspecialchars. {!! $note !!} becomes <?php echo $note; ?>. A Blade comment {{-- ... --}} is dropped and never reaches the browser.
Conditions and loops
These are the directives (Blade commands that start with @) for conditions and loops:
| Directive | Meaning | Closed with |
|---|---|---|
@if (...) |
print when the condition is true | @endif |
@elseif (...), @else |
other branches of @if |
|
@foreach ($books as $book) |
repeat for every item of the array | @endforeach |
@forelse ($books as $book) |
like @foreach, plus @empty |
@endforelse |
With the three books from the controller above, the list on the page becomes:
- The Rainbow Troops Available
- This Earth of Mankind All on loan
- Beauty Is a Wound Available
When $books is empty, @foreach prints nothing and the <ul> stays empty. @forelse has an @empty branch for that case:
@forelse ($books as $book)
<li>{{ $book['title'] }}</li>
@empty
<li>No books yet.</li>
@endforelse
Inside a loop, Blade gives you a $loop variable. $loop->iteration is the number of the pass, starting at 1. $loop->first is true on the first pass, and $loop->last is true on the last pass.
Layouts: @extends, @section, @yield
The parts every page shares (head, header, footer) are written once in a layout, which is a parent template. In the Library app, the layout is resources/views/layouts/app.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>@yield('title', 'Library')</title>
</head>
<body>
<header>Library</header>
@yield('content')
</body>
</html>
@yield('content')is a hole that the child page fills. The child page is a view that uses this layout.@yield('title', 'Library')has a default, for a child page that doesn't filltitle.- In the child page,
@extends('layouts.app')picks the layout,@section('content') ... @endsectionfills thecontenthole, and@section('title', 'Book List')fillstitlein one line. - The result is one whole page with
<title>Book List</title>, and the Library header above the book list.
Blade also has components for small pieces used again and again, like a button or a card. For example, the file resources/views/components/alert.blade.php is used with the tag <x-alert>.
A layout can also be a component. The Laravel 13 docs even show this way first. Pick one, then keep using it in a project:
| Way | In the layout file | In the child page |
|---|---|---|
| Template inheritance (above) | @yield('content') in layouts/app.blade.php |
@extends and @section |
| Component | {{ $slot }} and {{ $title ?? 'Library' }} in components/layout.blade.php |
<x-layout title="Book List"> ... </x-layout> |
In the component way, {{ $slot }} is filled with everything written between <x-layout title="Book List"> and </x-layout>, and the attribute title="Book List" becomes the variable $title.
⚠️ Blade pages that break or let scripts in
{!! !!}for user data. A door for XSS: a user's script runs too. Use{{ }}.- A missing closer.
@ifwithout@endifor@foreachwithout@endforeachbreaks the compiled PHP, and the page shows an error. - Writing the ending in the view name.
view('profile.blade.php')fails withView [profile.blade.php] not found.Writeview('profile'). - Forgetting to send the data. A variable that isn't in the
view()array gives the errorUndefined variable $note. - A form without
@csrfand@method. An HTML form can only sendGETandPOST. APOSTwithout a CSRF token can be answered419(the Request & Response lesson). Write these two directives inside the<form>:
<form action="{{ route('books.update', $book->id) }}" method="POST">
@csrf
@method('PUT')
<input name="title" value="{{ $book->title }}">
<button>Save</button>
</form>
@csrf writes a hidden _token input, which holds the CSRF token. @method('PUT') writes a _method input with the value PUT. Laravel then runs the PUT /books/{book} route, even though the browser sends POST. In this form, $book is an object, not an array like in the earlier example, so its values are read with ->, for example $book->title.
TL;DR: A view is a Blade template file: HTML with blanks for data. Views are stored in resources/views with the .blade.php ending, and a controller calls one with view('books.index', ['books' => $books]): a dot marks a folder boundary, and each array key becomes a variable. {{ $x }} prints safely: through e(), HTML characters such as < show as plain text. In contrast, {!! $x !!} prints raw and is only for your own HTML. @if/@elseif/@else/@endif for conditions, @foreach/@endforeach for loops, and @forelse/@empty/@endforelse when the data may be empty. A layout (a parent template) uses @yield for the holes to fill, and its child page uses @extends plus @section. Blade is compiled (turned) into plain PHP in storage/framework/views.
⚡ Hand data to a view
Write:
return view('books.index', ['books' => $books]);
Meaning: A view is a Blade template file: HTML with blanks for data. 'books.index' means the file resources/views/books/index.blade.php: a dot marks a folder boundary, and the .blade.php ending isn't written. Each array key becomes a variable in the view, so 'books' becomes $books.
⚡ {{ }} prints safely
Guess first: in a view, {{ $note }} prints the variable $note. $note holds New <b>books</b> arrive Monday. Does the word "books" come out bold?
No. {{ }} turns < into <, a code that shows as a plain < sign, so the browser shows the text as is, including <b>.
Meaning: Always use {{ }}. {!! !!} prints raw, without making it safe, and if the content comes from a user, a <script> inside it runs too. Use {!! !!} only for HTML you wrote yourself.
⚡ Loops and conditions
Write:
@foreach ($books as $book)
<li>
{{ $book['title'] }}
@if ($book['stock'] > 0)
<b>Available</b>
@else
<i>All on loan</i>
@endif
</li>
@endforeach
Meaning: @foreach repeats its body for every book in $books. @if picks a branch: Available when the stock is more than 0, and All on loan when it isn't. Every opener needs its closer: @if without @endif makes the page show an error.