0
0
LaravelHow-ToBeginner · 3 min read

How to Use @yield in Blade Templates in Laravel

In Laravel Blade templates, use @yield('sectionName') to define a placeholder in a layout where child views can inject content. The child view uses @section('sectionName') to provide content that replaces the @yield placeholder when rendered.
📐

Syntax

The @yield directive defines a placeholder in a Blade layout where content from child views will be inserted. It takes one required argument, the name of the section as a string.

Example parts:

  • @yield('content'): Placeholder named 'content'.
  • The child view uses @section('content') to fill this placeholder.
php
@yield('sectionName')
💻

Example

This example shows a layout file defining a @yield('title') and @yield('content') placeholder. The child view fills these sections with @section. When rendered, the layout displays the child's content in the placeholders.

php
{{-- resources/views/layouts/app.blade.php --}}
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    <header><h1>My Website</h1></header>
    <main>
        @yield('content')
    </main>
    <footer>© 2024</footer>
</body>
</html>

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

@section('title', 'Home Page')

@section('content')
    <p>Welcome to the home page!</p>
@endsection
Output
<html> <head> <title>Home Page</title> </head> <body> <header><h1>My Website</h1></header> <main> <p>Welcome to the home page!</p> </main> <footer>© 2024</footer> </body> </html>
⚠️

Common Pitfalls

  • Forgetting to define a matching @section in the child view causes @yield to output nothing.
  • Using @yield without quotes or with a typo in the section name will break the layout.
  • Defining multiple @section blocks with the same name in a child view can cause unexpected results.
  • Remember to use @endsection to close the section unless using the short syntax @section('name', 'content').
php
{{-- Wrong: missing quotes --}}
@yield(content)

{{-- Right: with quotes --}}
@yield('content')
📊

Quick Reference

DirectivePurposeUsage Example
@yieldDefines a placeholder in a layout@yield('sectionName')
@sectionDefines content for a section in a child view@section('sectionName') ... @endsection
@extendsSpecifies the layout a view inherits@extends('layouts.app')
@section short syntaxDefines a section with one line content@section('title', 'Page Title')

Key Takeaways

Use @yield in layouts to create placeholders for child view content.
Child views fill @yield placeholders using @section with matching names.
Always wrap section names in quotes in @yield and @section directives.
Use @extends in child views to specify which layout to use.
Missing @section for a @yield results in empty output for that section.