> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Blade templates

> An introduction to Laravel's Blade templating engine: directives, layouts, components, and practical examples.

## Introduction

Blade is the simple yet powerful templating engine included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. All Blade templates are compiled into plain PHP and cached, so Blade adds virtually zero overhead to your application.

Blade template files use the `.blade.php` extension and are stored in the `resources/views` directory.

```php theme={null}
Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});
```

## Displaying data

Display data passed to a Blade view by wrapping the variable in double curly braces:

```blade theme={null}
Hello, {{ $name }}.
```

<Info>
  Blade's `{{ }}` syntax automatically passes output through PHP's `htmlspecialchars` function to prevent XSS attacks.
</Info>

You can also display the result of any PHP expression:

```blade theme={null}
Current UNIX timestamp: {{ time() }}
```

### Unescaped output

Use the `{!! !!}` syntax when you need to render raw HTML without escaping:

```blade theme={null}
Hello, {!! $name !!}.
```

<Warning>
  Always use `{{ }}` for user-supplied data. Using `{!! !!}` with untrusted input creates XSS vulnerabilities.
</Warning>

### Coexisting with JavaScript frameworks

When your JavaScript framework also uses curly brace syntax, prefix the expression with `@` to tell Blade to leave it alone:

```blade theme={null}
<h1>Laravel</h1>

Hello, @{{ name }}.
```

Blade removes the `@` symbol, and `{{ name }}` is sent as-is to the browser for your JavaScript framework to render.

<Info>
  If you want to compare Blade with Livewire, Inertia, and SPA-style setups, see [Frontend](/en/frontend).
</Info>

## Blade directives

### Conditionals

```blade theme={null}
@if (count($records) === 1)
    There is one record.
@elseif (count($records) > 1)
    There are multiple records.
@else
    There are no records.
@endif
```

Use `@unless` to express "if not":

```blade theme={null}
@unless (Auth::check())
    You are not signed in.
@endunless
```

Check whether a variable is defined or non-empty with `@isset` and `@empty`:

```blade theme={null}
@isset($records)
    {{-- $records is defined and not null --}}
@endisset

@empty($records)
    {{-- $records is "empty" --}}
@endempty
```

### Authentication directives

```blade theme={null}
@auth
    {{-- Content for authenticated users --}}
@endauth

@guest
    {{-- Content for unauthenticated users --}}
@endguest
```

### Switch statements

```blade theme={null}
@switch($i)
    @case(1)
        First case...
        @break

    @case(2)
        Second case...
        @break

    @default
        Default case...
@endswitch
```

### Loops

Blade provides convenient directives for every common loop type:

```blade theme={null}
@for ($i = 0; $i < 10; $i++)
    Current value: {{ $i }}
@endfor

@foreach ($users as $user)
    <p>User: {{ $user->name }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users found.</p>
@endforelse

@while (true)
    <p>Looping forever.</p>
@endwhile
```

Use `@break` and `@continue` to control loop execution:

```blade theme={null}
@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach
```

You can also pass a condition directly to the directive:

```blade theme={null}
@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach
```

### The loop variable

Inside `@foreach` loops, the `$loop` variable gives you useful information about the current iteration:

```blade theme={null}
@foreach ($users as $user)
    @if ($loop->first)
        This is the first iteration.
    @endif

    @if ($loop->last)
        This is the last iteration.
    @endif

    <p>User: {{ $user->name }}</p>
@endforeach
```

| Property           | Description                         |
| ------------------ | ----------------------------------- |
| `$loop->index`     | Current loop index (zero-based)     |
| `$loop->iteration` | Current iteration count (one-based) |
| `$loop->remaining` | Remaining iterations                |
| `$loop->count`     | Total number of items               |
| `$loop->first`     | Whether this is the first iteration |
| `$loop->last`      | Whether this is the last iteration  |
| `$loop->even`      | Whether this is an even iteration   |
| `$loop->odd`       | Whether this is an odd iteration    |
| `$loop->depth`     | Nesting depth of the current loop   |
| `$loop->parent`    | Parent loop variable when nested    |

## Comments

Blade comments are never included in the rendered HTML:

```blade theme={null}
{{-- This comment will not appear in the rendered HTML --}}
```

## Layouts

### Component-based layouts

Using Blade components is the recommended approach for building layouts in modern Laravel applications.

First, create a layout component:

```blade theme={null}
<!-- resources/views/components/layout.blade.php -->
<html>
    <head>
        <title>{{ $title ?? 'My App' }}</title>
    </head>
    <body>
        <header>
            <nav>
                <!-- Navigation -->
            </nav>
        </header>

        <main>
            {{ $slot }}
        </main>
    </body>
</html>
```

Then use the layout in a view:

```blade theme={null}
<!-- resources/views/dashboard.blade.php -->
<x-layout>
    <x-slot:title>Dashboard</x-slot>

    <h1>Dashboard</h1>
    <p>Welcome!</p>
</x-layout>
```

### Template inheritance

The classic approach uses `@extends`, `@section`, and `@yield`:

**Defining the parent layout:**

```blade theme={null}
<!-- resources/views/layouts/app.blade.php -->
<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            Default sidebar content
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>
```

**Extending the layout in a child view:**

```blade theme={null}
<!-- resources/views/child.blade.php -->
@extends('layouts.app')

@section('title', 'Child Page')

@section('sidebar')
    @parent

    <p>Additional sidebar content</p>
@endsection

@section('content')
    <p>Main content here.</p>
@endsection
```

<Info>
  `@parent` lets you append to the parent's `@section` content instead of replacing it.
</Info>

## Including sub-views

Use `@include` to embed another Blade view. All variables available in the parent view are automatically available in the included view:

```blade theme={null}
<div>
    @include('shared.errors')

    <form>
        <!-- Form content -->
    </form>
</div>
```

Pass additional variables when including a view:

```blade theme={null}
@include('view.name', ['status' => 'complete'])
```

## CSRF protection in forms

HTML forms in the `web` routes file that send `POST`, `PUT`, `PATCH`, or `DELETE` requests must include the `@csrf` directive:

```blade theme={null}
<form method="POST" action="/profile">
    @csrf

    <!-- Form fields -->
</form>
```

To send `PUT`, `PATCH`, or `DELETE` requests from an HTML form, use the `@method` directive:

```blade theme={null}
<form method="POST" action="/post/1">
    @csrf
    @method('DELETE')

    <button type="submit">Delete</button>
</form>
```

<Info>
  See [CSRF protection](/en/csrf) for origin verification, token fallback behavior, and AJAX header strategies (`X-CSRF-TOKEN` / `X-XSRF-TOKEN`).
</Info>

## Summary

<AccordionGroup>
  <Accordion title="Displaying data">
    `{{ $variable }}` for escaped output, `{!! $variable !!}` for raw (unescaped) output.
  </Accordion>

  <Accordion title="Conditionals">
    `@if`, `@elseif`, `@else`, `@endif`, `@unless`, `@isset`, `@empty`, `@auth`, `@guest`.
  </Accordion>

  <Accordion title="Loops">
    `@for`, `@foreach`, `@forelse`, `@while` with `$loop` variable for iteration metadata.
  </Accordion>

  <Accordion title="Layouts">
    Component-based layouts (`<x-layout>` with `{{ $slot }}`) or template inheritance (`@extends`, `@section`, `@yield`).
  </Accordion>

  <Accordion title="Sub-views">
    `@include` to embed reusable view partials.
  </Accordion>
</AccordionGroup>


## Related topics

- [HTTP Tests](/en/http-tests.md)
- [Views](/en/views.md)
- [Routing](/en/routing.md)
- [Vite and Asset Bundling](/en/vite.md)
- [Authorization](/en/authorization.md)
