How to Use Blade Layouts in Laravel


Blade layouts are a powerful feature in Laravel, allowing you to create a consistent structure for your web application's views. With Blade layouts, you can define a master template and extend it in various pages, making it easy to maintain a uniform design and structure. In this guide, we'll explore how to use Blade layouts effectively in Laravel.


Defining a Master Layout


The first step is to define a master layout that serves as the common structure for your application. This layout typically includes the HTML structure, header, footer, and any other elements that should be consistent across all pages. You can create a master layout in the `resources/views/layouts` directory, for example, `resources/views/layouts/app.blade.php`:


        
<html>
<head>
<title>@yield('title') - My App</title>
</head>
<body>
<header>My App Header</header>
<main>
@yield('content')
</main>
<footer>My App Footer</footer>
</body>
</html>

In this example, the `@yield` directive is used to define sections where content will be inserted in child views.


Extending the Master Layout


To use the master layout in a child view, you can extend it by using the `@extends` directive. Create a new Blade view, and within it, specify the master layout to extend:


        
@extends('layouts.app')
@section('title', 'Home')
@section('content')
<h1>Welcome to My App</h1>
<p>This is the home page content.</p>
@endsection

In this child view, the `@extends` directive indicates that it extends the `app` layout. The `@section` directives define content for the `title` and `content` sections.


Nesting Layouts


You can also nest layouts, allowing for more complex structures. For example, you can create a `dashboard` layout that extends the `app` layout. Child views can then extend the `dashboard` layout to build upon the `app` layout:


        
@extends('layouts.dashboard')
@section('title', 'Dashboard')
@section('content')
<h1>Dashboard</h1>
<p>This is the dashboard content.</p>
@endsection

Conclusion


Blade layouts in Laravel provide a convenient way to create a consistent and structured design for your web application. By defining a master layout and extending it in child views, you can maintain a unified look and feel across your application while keeping your code organized and DRY (Don't Repeat Yourself). As you become more experienced with Laravel, you can explore advanced layout features like nested layouts, conditional sections, and sharing data with views.


For further learning, consult the official Laravel documentation and explore practical tutorials and examples related to using Blade layouts in Laravel web development.