Blade advanced

Components

Components are reusable Blade pieces with a tag syntax. An alert box, a card, or a button written once can be dropped into any page.

Component classes live in app/View/Components, and their templates live in resources/views/components. The tag below renders the alert template.

<x-alert type="success"> Profile saved! </x-alert>

Slots

Whatever you place between the opening and closing tags becomes the slot variable inside the component. Named slots pass extra named chunks alongside the main content.

<x-card> <x-slot:title>Hello</x-slot:title> Body text goes here. </x-card>

The card template prints the named title and the main slot where the body belongs.

<div class="card"> <h2>{{ $title }}</h2> {{ $slot }} </div>

Props

Props are the declared inputs of a component, listed at the top of its template with defaults. Callers pass them as tag attributes, like function arguments.

@props(["type" => "info"]) <div class="alert-{{ $type }}"> {{ $slot }} </div>

When components win

Reach for a component when the same markup appears on three or more pages, or when a block takes options like a type or a title. One tag then replaces a copied block.

Keep one-off page markup as plain Blade. Components pay off through reuse, not through ceremony.

<!-- repeated markup on every page --> <div class="alert">Saved!</div> <!-- the same box as a component --> <x-alert>Saved!</x-alert>

Next: Migrations

Article author: Arthur Isaev