Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 67 ยท Views and Blade

Layouts, Components and Slots

Build reusable Laravel views with Blade components: anonymous and class components, slots, the attributes bag, @props, layouts, @stack and @push, @include.

Nearly every page of a site shares the same frame: a header, a navigation bar, a footer. Many pages also repeat smaller pieces, such as alerts, cards and buttons. Copying that markup everywhere means one design change turns into thirty edits. Blade solves this with components: reusable pieces of template with their own inputs, used with tags that look like HTML, such as <x-alert type="error">.

This lesson covers the modern component style that Laravel recommends: anonymous components, class components, slots, the attributes bag, and layouts written as components. At the end you meet @stack, @include and the older @extends layout style, because you will still meet them in existing projects.

The framework code is read-only here, since Laravel does not run on this site. The runnable examples are a small plain-PHP renderer that expands <x-...> tags, so you can watch slots and attributes flow into a component.

Anonymous components

The simplest component is just a Blade file in resources/views/components. The file name becomes the tag name: components/alert.blade.php is used as <x-alert>.

BLADE
{{-- resources/views/components/alert.blade.php --}}
@props(['type' => 'info'])

<div {{ $attributes->merge(['class' => "alert alert-$type"]) }}>
    {{ $slot }}
</div>
BLADE
{{-- any view --}}
<x-alert type="error" class="mb-4" id="form-errors">
    Please fix the highlighted fields.
</x-alert>

Four ideas are at work:

  • @props declares the inputs and their defaults. Attributes named in @props become variables ($type). Everything else stays in the $attributes bag.
  • $slot holds whatever you put between the opening and closing tags.
  • $attributes is the bag of leftover attributes (class, id, data-*, wire:click and so on). Printing it adds them to the element, and merge() combines your defaults with what the caller passed. Classes are joined; for other attributes the caller's value wins.
  • A plain attribute passes a string. A leading colon passes a PHP expression: :count="$items->count()" gives the component an integer, while count="5" gives it the string "5". To print a literal colon attribute for a JavaScript framework, double it as ::class.

Subfolders use dots: components/forms/input.blade.php is <x-forms.input>. A file named index.blade.php inside a folder represents the folder name itself, so components/card/index.blade.php is <x-card>, with siblings such as <x-card.header>.

Slots

Besides the default slot you can define named slots with <x-slot:name>, which is handy for headers and footers:

BLADE
{{-- components/card.blade.php --}}
<section {{ $attributes->class(['rounded border p-4']) }}>
    @isset($title)
        <h2>{{ $title }}</h2>
    @endisset

    {{ $slot }}

    @isset($footer)
        <footer>{{ $footer }}</footer>
    @endisset
</section>
BLADE
<x-card class="wide">
    <x-slot:title>Orders</x-slot:title>

    Two orders are late.

    <x-slot:footer>Updated at noon</x-slot:footer>
</x-card>

A slot is an object that prints as HTML, and it has helpers such as isEmpty(), isNotEmpty() and hasActualContent(). Everything outside the named slots becomes $slot. Slot contents are not escaped again when printed, because they are markup the page author wrote; the variables inside the slot were escaped when they were echoed.

Class components

When a component needs real logic, such as a query, a computed value or dependency injection, generate a class:

Terminal
php artisan make:component Alert

This creates app/View/Components/Alert.php and resources/views/components/alert.blade.php.

PHP
<?php

namespace App\View\Components;

use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class Alert extends Component
{
    public function __construct(
        public string $type = 'info',
        public string $message = '',
    ) {}

    public function icon(): string
    {
        return match ($this->type) {
            'error' => '!',
            'success' => 'ok',
            default => 'i',
        };
    }

    public function render(): View
    {
        return view('components.alert');
    }
}

Public properties and public methods are available in the Blade view ({{ $icon() }}). Constructor arguments come from the tag's attributes, and a kebab-case attribute maps to a camelCase argument, so alert-type="x" fills $alertType. The container resolves any type-hinted services in the constructor, as in a controller.

Choose anonymous components for presentation-only pieces and class components when the piece needs PHP behind it.

Layout components

A layout is simply a component whose slot is the page body. This is the style the Laravel starter kits use:

BLADE
{{-- resources/views/components/layout.blade.php --}}
@props(['title' => config('app.name')])
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{{ $title }}</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    @stack('head')
</head>
<body>
    <x-nav />
    <main>{{ $slot }}</main>
    @stack('scripts')
</body>
</html>
BLADE
{{-- resources/views/dashboard.blade.php --}}
<x-layout title="Dashboard">
    <h1>Hello, {{ $user->name }}</h1>
</x-layout>
flowchart TD
    V["dashboard.blade.php"] --> L["x-layout (title, slot)"]
    L --> N["x-nav"]
    L --> S["slot: the page body"]
    S --> A["x-card"]
    A --> B["x-alert"]

Components nest like HTML elements: the page fills the layout's slot, and the slot can hold more components.

A renderer you can run

The next example is not Laravel's compiler. It is a small stand-in that finds <x-name ...> tags (innermost first), pulls out named slots, splits props from the attribute bag and calls a component function. It shows the data flow that real Blade performs.

PHP Components with slots and an attributes bag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the output. The type prop turned into the alert-warning class, while id="notice" stayed in the bag and landed on the element. In the card, class="wide" was merged after the default card class. The empty <x-alert /> fell back to the default type info. Real Blade does the same, but it also compiles to PHP and supports expressions, @aware, dynamic components and much more.

Class components, resolved by name

Real Laravel instantiates a class component by matching tag attributes to constructor parameters. This stand-in does the same with reflection and converts kebab-case names to camelCase:

PHP Constructor arguments from attributes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that alert-type filled $alertType, the unmatched id became a plain attribute, and the message was escaped because the view echoed it with htmlspecialchars (the equivalent of {{ }}).

Stacks, includes and the older style

Stacks let a nested view add something to a distant place in the layout, such as a script that only one page needs. The layout declares the slot with @stack('scripts') and any view can add to it:

BLADE
@push('scripts')
    <script src="/js/chart.js"></script>
@endpush

@pushOnce('scripts')
    <script src="/js/shared.js"></script>
@endPushOnce

@prepend adds to the front instead. @pushOnce keeps a component used ten times from printing the same script ten times.

Includes drop another view in place, sharing the current variables:

BLADE
@include('partials.footer')
@include('partials.stats', ['total' => 42])
@includeIf('partials.banner')
@includeWhen($user->isAdmin(), 'partials.admin-bar')
@each('partials.post', $posts, 'post', 'partials.no-posts')

Prefer components for new work. They have explicit inputs, so they are easier to read and reuse.

Template inheritance is the original Blade layout style. A child view extends a parent and fills named sections:

BLADE
{{-- layouts/app.blade.php --}}
<title>@yield('title', 'My app')</title>
<body>
    @section('sidebar')
        <p>Default sidebar</p>
    @show
    @yield('content')
</body>
BLADE
{{-- child view --}}
@extends('layouts.app')

@section('title', 'Home')

@section('sidebar')
    @parent
    <p>More sidebar links</p>
@endsection

@section('content')
    <h1>Welcome</h1>
@endsection

@parent keeps the parent's section content and adds to it. It still works fully and you will meet it in older tutorials and packages. Both styles can coexist in one app.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which file defines the tag <x-forms.input> as an anonymous component?

    Anonymous components live under resources/views/components, and dots in the tag name map to subfolders.
  2. 2. What does $attributes->merge(['class' => 'btn']) do when the caller passes class="big"?

    Class values are joined (btn first, then big). For other attributes the caller's value takes precedence over your default.
  3. 3. How do you pass a PHP expression, not a string, to a component attribute?

    A colon prefix tells Blade to evaluate the value as PHP. Without it the value is a literal string.
  4. 4. When is a class component a better fit than an anonymous one?

    A class component can hold logic and dependencies; anonymous components are best for presentation only.
  5. 5. What is @pushOnce useful for?

    Without it, a component that pushes a script tag would print the tag once per use.

Summary

  • Components are reusable Blade pieces used as <x-name> tags; anonymous ones are files in resources/views/components.
  • @props declares inputs; the rest of the attributes live in $attributes, where merge() combines your defaults with the caller's.
  • $slot is the default content and <x-slot:name> defines named slots.
  • Class components (make:component) add PHP logic and constructor injection; kebab-case attributes map to camelCase arguments.
  • A layout is a component whose slot is the page, with @stack and @push for page-specific assets.
  • @include and @extends/@section/@yield are older but fully supported.

Next: Forms, CSRF and Assets with Vite