How to Use @extends in Blade Templates in Laravel
Use the
@extends directive in a Blade view to inherit a layout file. It tells Laravel which parent template to use, allowing you to reuse common HTML structure across pages.Syntax
The @extends directive is placed at the top of a Blade view file. It takes one argument: the name of the layout view you want to inherit, written as a string without the .blade.php extension.
Example parts:
@extends('layouts.app'): Inherits theapp.blade.phpfile inside thelayoutsfolder.
blade
@extends('layouts.app')Example
This example shows a child view that extends a layout called layouts.app. The child fills the content section defined in the layout.
blade
/* 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>My Website</title> </head> <body> <header> <h1>Welcome to My Website</h1> </header> <main> @yield('content') </main> <footer> <p>© 2024 My Website</p> </footer> </body> </html> /* resources/views/home.blade.php */ @extends('layouts.app') @section('content') <p>This is the home page content.</p> @endsection
Output
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Website</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>
<main>
<p>This is the home page content.</p>
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
Common Pitfalls
- Forgetting to place
@extendsat the very top of the Blade file can cause unexpected behavior. - Using incorrect view names or paths inside
@extendswill cause Laravel to throw a "view not found" error. - Not defining matching
@sectionand@yieldnames between the layout and child views leads to missing content.
blade
/* Wrong: @extends not at top */ @section('content') <p>Content here</p> @endsection @extends('layouts.app') /* Right: @extends at top */ @extends('layouts.app') @section('content') <p>Content here</p> @endsection
Quick Reference
@extends lets you reuse a layout file in Blade views.
- Place
@extends('layout.name')at the top of your view. - Use
@section('sectionName')to fill content areas defined by@yield('sectionName')in the layout. - Helps keep your HTML DRY (Don't Repeat Yourself).
Key Takeaways
Use @extends at the very top of a Blade view to inherit a layout.
The argument to @extends is the layout view name without the .blade.php extension.
Define matching @section blocks in the child view to fill @yield placeholders in the layout.
Incorrect view names or misplaced @extends cause errors or missing content.
Blade layouts help keep your views organized and avoid repeating HTML.