SyntaxStudy
Sign Up
Laravel Blade Layouts and Components
Laravel Beginner 1 min read

Blade Layouts and Components

Blade's template inheritance model uses @extends and @section to create reusable layouts. A parent layout defines named sections with @yield or @section/@show blocks, and child views populate those sections. This prevents repetition of common HTML structure like headers, footers, and navigation across many views. The @parent directive within a child section appends to rather than replaces the parent's section content. Blade components are a more modern and reusable alternative to includes and partials. A component is a pair of a PHP class (in app/Http/View/Components/) and a Blade template (in resources/views/components/). Components are used in templates as self-closing tags prefixed with x-: . Props declared in the component class are available as variables in the template. Anonymous components have no associated PHP class and are defined as pure Blade files in resources/views/components/. They are ideal for stateless UI elements like buttons, cards, and form inputs. The $attributes variable contains all HTML attributes passed to the component, and $slot contains the content placed between the opening and closing component tags.
Example
{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title', 'My App')</title>
    @stack('styles')
</head>
<body>
    @include('partials.nav')
    <main>@yield('content')</main>
    @include('partials.footer')
    @stack('scripts')
</body>
</html>

{{-- resources/views/components/alert.blade.php --}}
@props(['type' => 'info', 'dismissible' => false])
<div {{ $attributes->merge(['class' => 'alert alert-' . $type]) }}>
    {{ $slot }}
    @if($dismissible)
        <button type="button" class="close">&times;</button>
    @endif
</div>

{{-- Usage in a child view --}}
@extends('layouts.app')
@section('title', 'Dashboard')
@section('content')
    <x-alert type="success" :dismissible="true">
        Your profile has been updated.
    </x-alert>
    <h1>Welcome back!</h1>
@endsection