HTML with Laravel
By the end of this lesson you will be able to write the HTML of a Laravel page with Blade, Laravel's template language. You will print data safely, build one layout for every page, link to routes and assets, and create a form that sends a security token, shows validation errors next to the right field and keeps what the visitor typed. You will also see the exact HTML that Blade sends to the browser.
What you should know first: HTML with PHP & MySQL, Secure Form Handling and Cross-Site Scripting (XSS) Prevention. The Laravel course teaches the framework itself; here we focus on the HTML. HTML Integration with Laravel goes deeper later.
Where HTML lives in a Laravel app
Laravel is a popular PHP framework: a ready-made structure for routes, database access, security and templates. This lesson uses Laravel 13, released on 17 March 2026, which needs PHP 8.3 or newer.
Your HTML lives in Blade templates: files ending in .blade.php inside resources/views. Blade adds short commands, such as {{ }} for printing and @foreach for loops. The first time a view is used, Laravel compiles it into ordinary PHP and caches it in storage/framework/views. The browser, as always, receives only the finished HTML.
Think of a wedding card printer in Pune. The design, border and wording are fixed on the template; only the names, date and venue change for each family. A Blade view is that template, and the data from your route or controller fills the gaps.
resources/views/
components/
layout.blade.php -> <x-layout> (shared page shell)
books/
index.blade.php -> view('books.index')
enquiry.blade.php -> view('enquiry')A dot in a view name means a folder: view('books.index') loads resources/views/books/index.blade.php.
Printing data: escaped and raw
| Blade | Becomes | Use it for |
|---|---|---|
{{ $book->title }} | Escaped text (through htmlspecialchars()) | Almost everything |
{!! $html !!} | Raw HTML, printed as it is | Only HTML you fully trust or have sanitised |
{{-- note --}} | Nothing: a Blade comment | Notes that must not reach the browser |
@{{ name }} | The text {{ name }} | Leaving braces for a JavaScript framework such as Vue |
{{ }} is the safe default. It turns <, >, & and quotes into entities, exactly like the e() helper you wrote in plain PHP. {!! !!} switches that protection off. A product description written by a seller, printed with {!! !!}, can carry a <script>. If you truly need user HTML, such as a formatted review, clean it with a sanitiser library first.
Normal HTML comments (<!-- -->) are sent to the browser, so anyone can read them with View Source. Use {{-- --}} for private notes.
Step 1: one layout for every page
Modern Laravel builds layouts as components. A component is a view in resources/views/components, used with an <x-...> tag. This is components/layout.blade.php:
@props(['title'])
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ $title }} | Pune Book Depot</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
<header><a href="{{ route('home') }}">Pune Book Depot</a></header>
<main>
{{ $slot }}
</main>
</body>
</html>@props(['title']) declares that the component accepts a title attribute. {{ $slot }} is where the page's own content goes. The lang value comes from the app's locale setting (en by default), so the whole site gets a correct lang from one place.
Step 2: a page that loops over data
The route loads books from the database with Eloquent, Laravel's database layer, and passes them to the view:
Route::get('/books', function () {
return view('books.index', [
'books' => Book::orderBy('title')->get(),
]);
})->name('books.index');
Route::get('/books/{book}', fn (Book $book) => $book->title)->name('books.show');The view books/index.blade.php wraps its content in the layout:
<x-layout title="Books">
<h1>Books in stock</h1>
<ul class="cards">
@foreach ($books as $book)
<li class="card">
<h2>{{ $book->title }}</h2>
<p>₹{{ number_format($book->price, 2) }}</p>
<a href="{{ route('books.show', $book) }}">Details</a>
</li>
@endforeach
</ul>
</x-layout>The database held three books, one with an & in its title and one where a seller had typed HTML into the title box. Opening /books returned this HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Books | Pune Book Depot</title>
<link rel="preload" as="style" href="http://localhost:8000/build/assets/app-DwXdhIKi.css" /><link rel="modulepreload" as="script" href="http://localhost:8000/build/assets/app-BvRk9kiK.js" /><link rel="stylesheet" href="http://localhost:8000/build/assets/app-DwXdhIKi.css" /><script type="module" src="http://localhost:8000/build/assets/app-BvRk9kiK.js"></script></head>
<body>
<header><a href="http://localhost:8000">Pune Book Depot</a></header>
<main>
<h1>Books in stock</h1>
<ul class="cards">
<li class="card">
<h2>Godan & Nirmala</h2>
<p>₹350.00</p>
<a href="http://localhost:8000/books/2">Details</a>
</li>
<li class="card">
<h2>Ignited Minds <b>Bestseller</b></h2>
<p>₹249.00</p>
<a href="http://localhost:8000/books/3">Details</a>
</li>
<li class="card">
<h2>Wings of Fire</h2>
<p>₹299.00</p>
<a href="http://localhost:8000/books/1">Details</a>
</li>
</ul>
</main>
</body>
</html>Look at the first two cards. & became &, and the seller's <b> tags arrived as harmless text. route('books.show', $book) built a full URL from the route's name and the book's id, so if the URL pattern ever changes, every link updates by itself. Here is the same output running in the browser (the Vite tags are removed because those files exist only on the server):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Books | Pune Book Depot</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
.cards { list-style: none; padding: 0; display: grid; gap: 12px;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); }
.card { border: 1px solid #ccc; border-radius: 8px; padding: 12px; }
.card h2 { font-size: 1.05rem; margin: 0 0 6px; }
</style>
</head>
<body>
<header><a href="http://localhost:8000">Pune Book Depot</a></header>
<main>
<h1>Books in stock</h1>
<ul class="cards">
<li class="card">
<h2>Godan & Nirmala</h2>
<p>₹350.00</p>
<a href="http://localhost:8000/books/2">Details</a>
</li>
<li class="card">
<h2>Ignited Minds <b>Bestseller</b></h2>
<p>₹249.00</p>
<a href="http://localhost:8000/books/3">Details</a>
</li>
<li class="card">
<h2>Wings of Fire</h2>
<p>₹299.00</p>
<a href="http://localhost:8000/books/1">Details</a>
</li>
</ul>
</main>
</body>
</html>The visitor sees Ignited Minds <b>Bestseller</b> with the tags as visible text. That looks odd, but it is safe, and it tells the shop to clean its data. Had the view used {!! $book->title !!}, any tag a seller typed would have become real markup.
Step 3: links and assets
Never hard-code your own URLs in Blade. These helpers build them for you:
| Helper | Example output | Use |
|---|---|---|
route('books.show', $book) | http://localhost:8000/books/1 | Links to your own pages, by route name |
url('/about') | http://localhost:8000/about | A path without a named route |
asset('images/logo.svg') | http://localhost:8000/images/logo.svg | Static files in the public folder |
@vite([...]) | <link> and <script> tags | CSS and JavaScript processed by Vite |
The host comes from the APP_URL setting, so the same code works on your laptop and on the live site. Vite is the build tool that bundles and minifies your CSS and JavaScript. After npm run build, the @vite line in the layout became:
<link rel="preload" as="style" href="http://localhost:8000/build/assets/app-DwXdhIKi.css" /><link rel="modulepreload" as="script" href="http://localhost:8000/build/assets/app-BvRk9kiK.js" /><link rel="stylesheet" href="http://localhost:8000/build/assets/app-DwXdhIKi.css" /><script type="module" src="http://localhost:8000/build/assets/app-BvRk9kiK.js"></script>
The file names contain a hash of their content, so they can be cached for a long time, as explained in Production Deployment & Optimization. The modulepreload and preload hints let the browser start downloading early. While you develop with npm run dev, the same @vite line points to the Vite development server instead, so changes appear instantly.
Step 4: a form with @csrf, errors and old values
A form in Blade is normal HTML with three Laravel helpers:
@csrfprints a hidden_tokenfield. Laravel rejects a POST, PUT, PATCH or DELETE request without a valid token (with status 419), which blocks cross-site request forgery, where another site tricks a logged-in visitor's browser into submitting your form. Laravel 13 also checks the request's origin, but you still include@csrfin every form.@error('field') ... @enderrorshows its content only when that field failed validation; inside it,$messageholds the error text.old('field')returns what the visitor typed before the failed submission, so they do not retype everything.
<x-layout title="Bulk order">
<h1>Bulk order for schools</h1>
@session('status')
<p role="status">{{ $value }}</p>
@endsession
<form method="POST" action="{{ route('enquiry.store') }}">
@csrf
<p>
<label for="school">School name</label>
<input id="school" name="school" value="{{ old('school') }}" required
@error('school') aria-invalid="true" aria-describedby="school-error" @enderror>
@error('school')
<span id="school-error" class="error">{{ $message }}</span>
@enderror
</p>
<p>
<label for="copies">Number of copies</label>
<input id="copies" name="copies" type="number" min="10" value="{{ old('copies') }}" required
@error('copies') aria-invalid="true" aria-describedby="copies-error" @enderror>
@error('copies')
<span id="copies-error" class="error">{{ $message }}</span>
@enderror
</p>
<button type="submit">Send enquiry</button>
</form>
</x-layout>The route validates the data. If validation fails, Laravel redirects back automatically with the errors and old input; if it passes, it redirects with a status message, which @session displays:
Route::view('/enquiry', 'enquiry')->name('enquiry.create');
Route::post('/enquiry', function (Request $request) {
$request->validate([
'school' => ['required', 'string', 'max:120'],
'copies' => ['required', 'integer', 'min:10'],
]);
return redirect()->route('enquiry.create')
->with('status', 'Thank you. We will call you within one working day.');
})->name('enquiry.store');Submitting the school St. Mary's School, Kochi with 4 copies gave back this form (the token is shortened here):
<main>
<h1>Bulk order for schools</h1>
<form method="POST" action="http://localhost:8000/enquiry">
<input type="hidden" name="_token" value="LWXMrQIp..." autocomplete="off"> <p>
<label for="school">School name</label>
<input id="school" name="school" value="St. Mary's School, Kochi" required
>
</p>
<p>
<label for="copies">Number of copies</label>
<input id="copies" name="copies" type="number" min="10" value="4" required
aria-invalid="true" aria-describedby="copies-error" >
<span id="copies-error" class="error">The copies field must be at least 10.</span>
</p>
<button type="submit">Send enquiry</button>
</form>
</main>The school name came back escaped (' is the apostrophe), the copies field is marked aria-invalid="true", and the error text is linked with aria-describedby, so a screen reader reads it with the field. You can try the result in the browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bulk order | Pune Book Depot</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
label { display: block; font-weight: bold; }
input { padding: 6px; width: 16rem; max-width: 100%; }
[aria-invalid="true"] { border: 2px solid #b00020; }
.error { display: block; color: #b00020; }
</style>
</head>
<body>
<header><a href="http://localhost:8000">Pune Book Depot</a></header>
<main>
<h1>Bulk order for schools</h1>
<form method="POST" action="http://localhost:8000/enquiry">
<input type="hidden" name="_token" value="LWXMrQIp..." autocomplete="off"> <p>
<label for="school">School name</label>
<input id="school" name="school" value="St. Mary's School, Kochi" required
>
</p>
<p>
<label for="copies">Number of copies</label>
<input id="copies" name="copies" type="number" min="10" value="4" required
aria-invalid="true" aria-describedby="copies-error" >
<span id="copies-error" class="error">The copies field must be at least 10.</span>
</p>
<button type="submit">Send enquiry</button>
</form>
</main>
</body>
</html>Press Send enquiry: the browser itself stops the form, because 4 is below min="10". (Blade keeps the spaces and line breaks of your template, which is why the output looks untidy; browsers do not mind.) Browser validation gives instant hints, but the server rules in validate() are what protect your data. Forms that update or delete use method="POST" plus @method('PUT') or @method('DELETE'), which adds a hidden _method field, because HTML forms only send GET and POST.
Common mistakes
- Using
{!! !!}for convenience. It switches off escaping; use it only for trusted or sanitised HTML. - Forgetting
@csrf. The form fails with a 419 "Page Expired" error. - Hard-coded URLs such as
href="/books/{{ $book->id }}". Useroute()so links follow route changes. - Error messages not connected to fields. Add
aria-invalidandaria-describedbyinside@error. - Secrets in HTML comments.
<!-- -->reaches the browser;{{-- --}}does not. - Validating only in the browser.
requiredandmincan be bypassed; keep the rules invalidate().
Interview questions
1. What is the difference between {{ }} and {!! !!} in Blade?
{{ }} escapes the value with htmlspecialchars(), so any HTML in it is shown as text. {!! !!} prints the value raw, so HTML in it is rendered and scripts can run. Use {{ }} by default and {!! !!} only for trusted or sanitised HTML.
2. What does @csrf do?
It adds a hidden _token input containing the session's CSRF token. Laravel's middleware compares it on every state-changing request and rejects requests without a valid token with status 419. This stops other websites from submitting forms on behalf of a logged-in user.
3. How do you show validation errors and keep the user's input in Blade?
Use @error('field') with $message to print the error for a field, and value="{{ old('field') }}" to refill it. When validate() fails, Laravel redirects back and flashes both the errors and the old input into the session. Adding aria-invalid and aria-describedby makes the error accessible.
4. Components or @extends layouts: which would you use?
For new code, components such as <x-layout>, because the same idea also covers small reusable pieces and their attributes are explicit. @extends, @section and @yield still work and appear in many existing projects. Both produce the same HTML, so a team should pick one style per project.
5. Why use route() instead of writing URLs by hand?
route() builds the URL from the route's name and parameters, so if the URL pattern changes, every link updates automatically. It also uses APP_URL, so links are correct on every environment. Hand-written URLs break silently.
Key points
- Blade views live in
resources/viewsas.blade.phpfiles and compile to plain PHP; the browser only sees HTML. {{ }}escapes output and is the default;{!! !!}prints raw HTML and is a common XSS cause.- Build the page shell once as a
<x-layout>component with{{ $slot }};@extends/@yieldis the older style. - Use
route(),url()andasset()for links and files, and@vitefor hashed CSS and JavaScript. - Every form needs
@csrf; show errors with@errorand$message, refill fields withold(), and add@methodfor PUT and DELETE. - Keep server validation in
validate()and connect error text to fields with ARIA attributes.
Exercise
Create an "Edit book" form for the Pune Book Depot. It must use the <x-layout> component, send a PUT request to a route named books.update, include the CSRF token, and have a title field and a category <select> (Fiction, Biography, Exam guides). Refill both from old(), falling back to the book's current values, show each field's error accessibly, and make the selected category stay selected after a failed submission.
Show solution
<x-layout title="Edit {{ $book->title }}">
<h1>Edit book</h1>
<form method="POST" action="{{ route('books.update', $book->id) }}">
@csrf
@method('PUT')
<p>
<label for="title">Title</label>
<input id="title" name="title" value="{{ old('title', $book->title) }}" required
@error('title') aria-invalid="true" aria-describedby="title-error" @enderror>
@error('title')
<span id="title-error" class="error">{{ $message }}</span>
@enderror
</p>
<p>
<label for="category">Category</label>
<select id="category" name="category"
@error('category') aria-invalid="true" aria-describedby="category-error" @enderror>
@foreach (['Fiction', 'Biography', 'Exam guides'] as $category)
<option @selected(old('category', $book->category) === $category)>{{ $category }}</option>
@endforeach
</select>
@error('category')
<span id="category-error" class="error">{{ $message }}</span>
@enderror
</p>
<button type="submit">Save changes</button>
</form>
</x-layout>@method('PUT') adds a hidden _method field, so Laravel routes the POST to the books.update PUT route. old('title', $book->title) uses the typed value after a failed submission and the saved value the first time. @selected(...) prints selected only on the matching option. When we submitted an empty title with "Exam guides" chosen, the page came back with aria-invalid="true" on the title, the message "The title field is required." and <option selected>Exam guides</option>. The route should also validate category with an in: rule, because a visitor can send any value.
Quick Quiz
1. Which Blade syntax prints a value with HTML escaping?
Double curly braces escape the value with htmlspecialchars().
2. A form without @csrf is submitted. What happens by default?
Laravel needs a valid CSRF token on POST, PUT, PATCH and DELETE requests.
3. How does an HTML form send a PUT request to Laravel?
HTML forms only support GET and POST, so Laravel reads a hidden _method field.
4. What does old('school') return after a failed validation?
Laravel flashes the old input to the session so the form can be refilled.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
