How to use the @include directive in Laravel

Blade directives are shortcut codes that help to implement basic PHP control structure. For example loop and conditional statements. It helps makes a code snippets clean and easier to understand. @include directive enables you to add another blade view in an existing view. In short, you may import an entire blade as a subset of an original parent blade file. This makes all variables accessible to the parent view that are in the included view.

You may use it as shown in the code snippet below.

        <!-- Form Contents -->

The included view also inherits the data that is available in the parent view. However, you can also pass an array with some extra data to the included view as shown below.

@include('error.blade', ['show' => 'data'])

In some cases a user might add a view which does not exists or is deleted. Laravel may throw an error in this case. However, Laravel exception handling techniques allows you to add an exception for this. You may use the @includeIf directive instead of the @include directive. This adds the view only if its available in the Laravel application and won’t throw an error if its not. You may use it as shown below.

@includeIf('error.blade', ['show' => 'data'])

Another exception is when you want to add a view based on a given Boolean condition. In such cases, you may change it to the @includeWhen directive and use as shown below.

@includeWhen($boolean, 'error.blade', ['show' => 'data'])

The $boolean variable can hold any condition, which when returns true, the corresponding view comes up. For example suppose you need to add a view when a user’s status is active. So you read the user status variable from the controller as the $boolean variable. When it is true, the embedded view will show up, otherwise it won’t.

You can enclose multiple error messages like validation error messages in a single blade and include them when required. For example, when Boolean variable of validation fails from controller.

Suppose if you have an array of views, and you need to choose one from them to show up. You can select the first view that exists in a Laravel application by using the @includeFirst directive as shown below.

@includeFirst(['error.blade', 'error_excep.blade', 'error_new.blade'], ['show' => 'data'])

If you are dealing with multiple error blades, and need to chose one. You can pass them as an array as shown above. The @includeFirst directive will read the first available blade and add it.