Laravel Blade Layouts

Laravel Blade Layouts

Blade layouts let you define a master template once and extend it in child views, avoiding repetition across pages.

1 - Defining a Layout

{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', 'My App')</title>
    @stack('styles')
</head>
<body>
    @include('layouts.nav')

    <main>
        @yield('content')
    </main>

    @stack('scripts')
</body>
</html>

2 - Extending a Layout

{{-- resources/views/posts/index.blade.php --}}
@extends('layouts.app')

@section('title', 'All Posts')

@section('content')
    <h1>Posts</h1>
    @foreach ($posts as $post)
        <h2>{{ $post->title }}</h2>
    @endforeach
@endsection

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

3 - Including Sub-Views

{{-- Include always --}}
@include('partials.alert')

{{-- Include only if the view exists --}}
@includeIf('partials.banner')

{{-- Include with extra data --}}
@include('partials.card', ['title' => $post->title])

4 - Components (Modern Alternative)

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

{{-- Usage --}}
<x-alert type="success">
    Profile updated successfully!
</x-alert>