Topics Blade Templating Components & Layouts
intermediate 16 min read

Components & Layouts

Blade components, layout inheritance, component classes, and anonymous components.

Blade Layouts


<!DOCTYPE html>
<html>
<head>
<title>@yield("title", "Default")</title>
@stack("styles")
</head>
<body>
<nav>@include("partials.nav")</nav>
<main>
@yield("content")
</main>
@stack("scripts")
</body>
</html>


@extends("layouts.app")

@section("title", "About Us")

@section("content")
<h1>About Us</h1>
<p>We build amazing applications with Laravel.</p>
@endsection

Blade Components

{{-- Create with: php artisan make:component Alert --}}

{{-- app/View/Components/Alert.php --}}
namespace App\View\Components;

use Illuminate\View\Component;

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

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

{{-- resources/views/components/alert.blade.php --}}
<div class="alert alert-{{ $type }}">
{{ $message ?? $slot }}
</div>

{{-- Usage --}}
<x-alert type="warning" message="Please verify your email." />
<x-alert type="success">Account created!</x-alert>

Anonymous Components

{{-- resources/views/components/button.blade.php --}}
<button {{ $attributes->merge([
"class" => "btn btn-".($type ?? "primary")
]) }}>
{{ $slot }}
</button>

{{-- Usage --}}
<x-button type="danger" class="mt-4">Delete</x-button>

Examples

<?php
// Create a Card component with title and slot
// php artisan make:component Card

// Card.php: public function __construct(public string \$title = 'Default') {}

// card.blade.php:
// <div class="card"><h2>{{ \$title }}</h2><div>{{ \$slot }}</div></div>

// Usage:
// <x-card title="Welcome"><p>Content here</p></x-card>

Your Notes

Sign in to take notes for this lesson.

Quiz

Blade Templating Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.