0
0
Laravelframework~5 mins

Including sub-views (@include) in Laravel

Choose your learning style9 modes available
Introduction

Including sub-views lets you reuse small parts of your page easily. It helps keep your code clean and organized.

You want to show the same header on many pages.
You have a footer that appears on every page.
You want to split a big page into smaller parts for easier editing.
You want to reuse a form or button design in multiple places.
Syntax
Laravel
@include('view.name')
The view name is the path to the Blade file without the .blade.php extension.
You can pass data to the included view using a second argument like @include('view.name', ['key' => 'value']).
Examples
This includes the header.blade.php file at this spot.
Laravel
@include('header')
This includes the partials/footer.blade.php file.
Laravel
@include('partials.footer')
This includes the alert.blade.php file and sends it data to show a success message.
Laravel
@include('alert', ['type' => 'success', 'message' => 'Saved!'])
Sample Program

This example shows a main layout that includes a header and footer sub-view. The header and footer are separate files, so you can reuse them on other pages easily.

Laravel
<!-- resources/views/layout.blade.php -->
<html>
  <body>
    @include('header')
    <main>
      <h1>Welcome to my site</h1>
      <p>Enjoy your stay!</p>
    </main>
    @include('footer')
  </body>
</html>

<!-- resources/views/header.blade.php -->
<header>
  <h2>Site Header</h2>
</header>

<!-- resources/views/footer.blade.php -->
<footer>
  <p>Ā© 2024 My Website</p>
</footer>
OutputSuccess
Important Notes

Use @include to keep your views DRY (Don't Repeat Yourself).

Passing data to included views helps make them flexible and reusable.

If the included view file is missing, Laravel will throw an error, so check your file paths carefully.

Summary

@include inserts a sub-view inside another view.

It helps reuse common parts like headers and footers.

You can pass data to customize the included sub-view.