How to Use @include in Blade Templates in Laravel
Use the
@include('view.name') directive in Blade to insert one Blade view inside another. This helps reuse common parts like headers or footers by referencing their view file names.Syntax
The @include directive inserts a Blade view inside another view. You write @include('view.name') where view.name is the path to the Blade file without the .blade.php extension.
You can also pass data as an array with @include('view.name', ['key' => 'value']) to share variables with the included view.
php
@include('partials.header') @include('partials.footer', ['year' => 2024])
Example
This example shows how to include a header and footer Blade file inside a main layout. The footer receives a variable year to display dynamically.
php
<!-- resources/views/layout.blade.php -->
<html>
<body>
@include('partials.header')
<h1>Welcome to my website</h1>
@include('partials.footer', ['year' => 2024])
</body>
</html>
<!-- resources/views/partials/header.blade.php -->
<header>
<nav>Navigation bar here</nav>
</header>
<!-- resources/views/partials/footer.blade.php -->
<footer>
<p>© {{ $year }} My Website</p>
</footer>Output
<html>
<body>
<header>
<nav>Navigation bar here</nav>
</header>
<h1>Welcome to my website</h1>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
Common Pitfalls
- Forgetting to use quotes around the view name causes syntax errors.
- Including a view that does not exist triggers an error; ensure the path is correct.
- Passing variables incorrectly (not as an array) will not share data with the included view.
- Using
@includeinside loops without unique keys can cause unexpected behavior in some cases.
php
<!-- Wrong: missing quotes --> @include(partials.header) <!-- Right: quotes around view name --> @include('partials.header') <!-- Wrong: passing variable as string --> @include('partials.footer', 'year') <!-- Right: passing variable as array --> @include('partials.footer', ['year' => 2024])
Quick Reference
Use @include('view.name') to insert a Blade view file. Pass data with @include('view.name', ['key' => 'value']). The included view can access passed variables directly.
| Usage | Description |
|---|---|
| @include('view.name') | Insert the specified Blade view. |
| @include('view.name', ['key' => 'value']) | Insert view and pass variables. |
| View file path | Use dot notation without .blade.php extension. |
| Variables in included view | Access passed variables by their keys. |
Key Takeaways
Use @include('view.name') to insert reusable Blade views easily.
Pass data as an array with @include to share variables with the included view.
Always use quotes around the view name to avoid syntax errors.
Check that the included view file exists to prevent runtime errors.
Included views can access passed variables directly by their keys.