Blade Templates
Laravel’s templating engine — clean syntax for putting data and logic into your HTML.
What you will learn
- Output data with {{ }}
- Loop and branch in Blade
- Pass data from controllers
Blade = HTML + data
Blade files end in .blade.php and live in resources/views. Output data with {{ }} (which safely escapes it), and use @ directives for logic.
<!-- resources/views/products/index.blade.php -->
<h1>Products</h1>
<ul>
@foreach ($products as $product)
<li>{{ $product }}</li>
@endforeach
</ul>
@if (count($products) === 0)
<p>No products yet.</p>
@endifReading this top to bottom: the @foreach ($products as $product) line loops over the $products list the controller sent in, and for each one it prints a <li> with {{ $product }} (the double curly braces print the value safely). @endforeach marks where the loop stops. Then @if (count($products) === 0) shows a friendly "No products yet." message only when the list is empty. Notice how every @ block has a matching @end... — that is how Blade knows where each piece begins and ends.
Note: Output (with three products):
Products
• Keyboard
• Mouse
• Monitor
The @if block prints nothing here because the list is not empty. Remove the products and you would instead see: No products yet.
| Blade | Does |
|---|---|
{{ $var }} | Print (auto-escaped, safe) |
@if / @endif | Condition |
@foreach / @endforeach | Loop |
@extends / @section | Layouts (next lesson) |
Tip: {{ }} automatically escapes output (prevents XSS — Cross-Site Scripting, an attack where someone sneaks <script> code into your page through a form). Escaping turns that code into harmless text, so {{ }} is the safe default. You almost never need the raw {!! !!} version.
Q. How do you print a variable in a Blade template?
✍️ Practice
- Render a list of items from controller data using
@foreach. - Show a “none yet” message with
@ifwhen the list is empty.
🏠 Homework
- Build a Blade page that displays an array of product names and prices.