Blade Templates

Blade is Laravel's templating engine for building HTML views.

Syntax{{ $variable }}

Blade templates live in resources/views and end in .blade.php. Use {{ }} to echo escaped data (protecting against XSS) and @-directives for logic.

Return a view from a controller with the view() helper.

Example

Example · php
<!-- resources/views/welcome.blade.php -->
<h1>Hello, {{ $name }}!</h1>
<p>You have {{ $count }} new messages.</p>

When to use it

  • A developer uses a Blade layout template to define the common HTML shell once and have every page extend it, avoiding duplication of the nav and footer.
  • A product card Blade component encapsulates the card HTML and is reused across the homepage, search results, and category pages with a single <x-product-card> tag.
  • An e-commerce back-end uses @foreach and @if directives in Blade templates instead of opening PHP tags, keeping the view files clean and readable.

More examples

Echo a variable safely

{{ }} echoes a value with HTML escaping (safe for user input); {!! !!} outputs raw HTML and should only be used with trusted content.

Example · php
{{-- Blade template: resources/views/greeting.blade.php --}}

<h1>Hello, {{ $name }}!</h1>

{{-- Double curly braces HTML-escape the value --}}
<p>You have {{ $messageCount }} messages.</p>

{{-- Use {!! ... !!} ONLY for trusted HTML --}}
<div>{!! $trustedHtml !!}</div>

Loop and conditional directives

Shows @foreach for iteration, @if/@else for conditions, and @forelse which combines a loop with an @empty fallback in one directive.

Example · php
@foreach ($products as $product)
    <div class="card">
        <h2>{{ $product->name }}</h2>
        @if ($product->stock > 0)
            <span class="badge-green">In Stock</span>
        @else
            <span class="badge-red">Out of Stock</span>
        @endif
    </div>
@endforeach

@forelse ($products as $product)
    <p>{{ $product->name }}</p>
@empty
    <p>No products found.</p>
@endforelse

Pass data to a view from a controller

Passes both the current product and a collection of related products to the Blade view as an associative array.

Example · php
// In a controller
public function show(Product $product): View
{
    $related = Product::where('category_id', $product->category_id)
        ->where('id', '!=', $product->id)
        ->take(4)
        ->get();

    return view('products.show', [
        'product' => $product,
        'related' => $related,
    ]);
}

Discussion

  • Be the first to comment on this lesson.