How to create and use Blade layout templates for consistent page structure in Laravel?

To create and use Blade layout templates for consistent page structure in Laravel, follow these steps:

  1. Create a new layout template file: In the resources/views/layouts directory, create a new Blade template file, e.g., app.blade.php. This file will serve as the base layout for all your pages.

  2. Define the basic structure in the layout template: In the app.blade.php file, define the basic HTML structure for your pages, including the <html>, <head>, and <body> tags. You can also add a navigation bar or any other common elements that will appear on all pages.

  3. Define the sections in the layout template: Within the <body> tags, define sections using the @yield directive. For example, you can define a content section where the content of each specific page will be injected. You can also define optional sections for specific page elements that might change across pages, such as a sidebar or footer.

<body> {{-- Navigation bar --}} <div class="content"> @yield('content') {{--section to inject content of each specific page--}} </div> {{-- Optional page element sections --}} {{-- Footer --}} </body>
  1. Create a new page template: Create a new Blade template file for each page in the resources/views directory. For example, create a welcome.blade.php file for your home page.

  2. Extend the layout template in the page template: In each page template, use the @extends directive to extend the layout template. Specify the name of the layout template file (without the .blade.php extension). For example:

@extends('layouts.app')
  1. Define the content of the page: In each page template, use the @section directive to define the content that will replace the @yield('content') section in the layout template. For example:
@section('content') <h1>Welcome to My Website</h1> <p>This is the home page.</p> @endsection
  1. Customize the page as needed: Add specific content and page elements to each page template using regular HTML and Blade syntax. You can also include CSS and JavaScript files, use Blade directives, or include other Blade templates using the @include directive.

Now, when you visit the URL corresponding to each page, Laravel will use the specified layout template and inject the content from the respective page template into the @yield('content') section. This provides consistent page structure across your Laravel application.