0
0
Laravelframework~3 mins

Why Template inheritance (@extends, @section, @yield) in Laravel? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change your website's header once and see it update everywhere instantly?

The Scenario

Imagine building a website where every page needs the same header, footer, and sidebar. You copy and paste the same HTML into every file. Then, you want to change the header color. You have to open every file and update it one by one.

The Problem

This manual approach is slow and risky. You might miss some files, causing inconsistent layouts. It's hard to keep the design uniform, and updating common parts becomes a frustrating chore.

The Solution

Template inheritance lets you define a base layout once, then create pages that fill in only the unique parts. Using @extends, @section, and @yield, Laravel automatically combines your layouts, so changes to the base affect all pages instantly.

Before vs After
Before
<!DOCTYPE html>
<html>
<head><title>Page 1</title></head>
<body>
<header>My Site</header>
<p>Content for page 1</p>
<footer>Footer info</footer>
</body>
</html>
After
@extends('base')
@section('content')
<p>Content for page 1</p>
@endsection
What It Enables

This makes building and maintaining websites faster, cleaner, and less error-prone by reusing layouts effortlessly.

Real Life Example

Think of a blog where every post shares the same header and footer. With template inheritance, you update the header once, and all posts reflect the change immediately.

Key Takeaways

Copy-pasting layouts is slow and error-prone.

Template inheritance centralizes common parts for easy updates.

@extends, @section, and @yield work together to build pages efficiently.