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>
@endsectionOutput
<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
@sectionin the child view causes@yieldto output nothing. - Using
@yieldwithout quotes or with a typo in the section name will break the layout. - Defining multiple
@sectionblocks with the same name in a child view can cause unexpected results. - Remember to use
@endsectionto close the section unless using the short syntax@section('name', 'content').
php
{{-- Wrong: missing quotes --}}
@yield(content)
{{-- Right: with quotes --}}
@yield('content')Quick Reference
| Directive | Purpose | Usage Example |
|---|---|---|
| @yield | Defines a placeholder in a layout | @yield('sectionName') |
| @section | Defines content for a section in a child view | @section('sectionName') ... @endsection |
| @extends | Specifies the layout a view inherits | @extends('layouts.app') |
| @section short syntax | Defines 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.