How to Use @section in Blade Templates in Laravel
In Laravel Blade templates, use
@section('name') to start a content section and @endsection to end it. This defines a named section that can be injected into a layout using @yield('name').Syntax
The @section directive defines a named content block in a Blade view. It starts with @section('sectionName') and ends with @endsection. The content inside is captured and can be displayed in a layout using @yield('sectionName').
php
@section('title')
Page Title Here
@endsectionExample
This example shows a Blade layout using @yield to display sections, and a child view defining those sections with @section.
php
{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@yield('title')</title>
</head>
<body>
<header>
<h1>@yield('header')</h1>
</header>
<main>
@yield('content')
</main>
</body>
</html>
{{-- resources/views/pages/home.blade.php --}}
@extends('layouts.app')
@section('title')
Home Page
@endsection
@section('header')
Welcome to My Site
@endsection
@section('content')
<p>This is the home page content.</p>
@endsectionOutput
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page</title>
</head>
<body>
<header>
<h1>Welcome to My Site</h1>
</header>
<main>
<p>This is the home page content.</p>
</main>
</body>
</html>
Common Pitfalls
- Forgetting to close a section with
@endsectioncauses errors or missing content. - Using the same section name multiple times without
@overwriteor@parentcan lead to unexpected content replacement. - Not using
@yieldin the layout means the section content won't display.
php
{{-- Wrong: Missing @endsection --}}
@section('content')
<p>Content without end</p>
{{-- Right: Properly closed section --}}
@section('content')
<p>Content with end</p>
@endsectionQuick Reference
| Directive | Purpose |
|---|---|
| @section('name') ... @endsection | Define a named content section |
| @yield('name') | Display the content of a named section in a layout |
| @extends('layout') | Specify the parent layout to extend |
| @parent | Include parent section content inside a child section |
| @overwrite | Replace parent section content completely |
Key Takeaways
Use @section('name') and @endsection to define content blocks in Blade views.
Display section content in layouts with @yield('name').
Always close sections with @endsection to avoid errors.
Use unique section names or @parent/@overwrite to manage content inheritance.
Combine @extends with @section to build layouts and pages cleanly.