Laravel Include
In Laravel Blade, the @include
directive is used to insert the contents of one Blade view into another. This is a powerful feature for reusing code and creating modular templates, which helps keep your views organized and maintainable.
Basic Syntax
To include a Blade view, use the @include
directive followed by the name of the view file you want to include. Do not include the .blade.php
extension.
Syntax:
@include('view.name')
Example:
If you have a view file resources/views/partials/header.blade.php
, you can include it in another view like this:
@include('partials.header')
Passing Data to Included Views
You can also pass data to the included view by providing an associative array as the second argument to the @include
directive.
Syntax:
@include('view.name', ['key' => 'value'])
Example:
If you want to pass a $title
variable to header.blade.php
, you can do:
In resources/views/partials/header.blade.php
:
<header> <h1>{{ $title }}</h1> </header>
In the main view:
@include('partials.header', ['title' => 'Welcome to My Site'])
This will render:
<header>
<h1>Welcome to My Site</h1>
</header>
Using Include with Conditionals
You can include views conditionally based on certain logic in your Blade template.
Example:
@if ($showHeader) @include('partials.header') @endif
In this example, the header
view is only included if $showHeader
is true.
Using Include with Loop
You can also use @include
inside loops to include the same partial view multiple times with different data.
Example:
In resources/views/partials/user.blade.php
:
<div> <p>{{ $user->name }}</p> </div>
In the main view:
@foreach ($users as $user) @include('partials.user', ['user' => $user]) @endforeach
This will render the user partial for each user in the $users
array.
Benefits of Using @include
- Modularity: Break down complex views into smaller, reusable components.
- Maintainability: Easier to manage and update shared pieces of UI.
- Readability: Keeps your Blade templates cleaner and more organized.
Summary
The @include
directive in Laravel Blade allows you to include one Blade view inside another, making it easy to reuse code and create modular templates. You can pass data to the included views, conditionally include views, and use them within loops to dynamically generate content. This promotes better organization, maintainability, and readability of your views.