Sling Academy
Home/PHP/Laravel – How to including Blade subviews

Laravel – How to including Blade subviews

Last updated: January 15, 2024

Introduction

Blade is the simple, powerful templating engine provided with Laravel. Among Blade’s robust features is the ability to include subviews, which are essentially partials that can be reused across different views. This not only makes your views more manageable by breaking them into logical sections, but it also promotes the DRY (Don’t Repeat Yourself) principle in your codebase. In this tutorial, we will walk through the basics to more complex uses of Blade subviews in Laravel.

Basic Usage of Include

At its simplest, including subviews in Blade is done via the @include directive. This directive takes the path of the view file relative to the resources/views directory as a parameter.

{!! Blade::include('folder.subview_name', ['some' => 'data']) !!}

For example, if you have a header that you want to include across various templates:

// resources/views/includes/header.blade.php

<header>
    <h1>My Website</h1>
    <nav>...</nav>
</header>

// Including the header in a different view
{!! Blade::include('includes.header') !!}

This will render the contents of header.blade.php wherever the @include directive is placed.

Passing Data to Subviews

A powerful feature of @include is the ability to pass data to the subview. Data can be passed either directly or through the parent view’s data:

// Passing data directly
{!! Blade::include('includes.header', ['some_key' => 'Some value']) !!}

// Passing data through parent view
{$some_key = 'Some value';}
{!! Blade::include('includes.header') !!}

In both examples, some_key would be available in the header.blade.php as a variable.

@each for Iterating Over Lists

Another useful directive in Blade is @each, which can iterate over a list and includes a view for each item. This is particularly useful for displaying items in an array or a Collection.

// Assuming {$users} is a list of user objects
{!! Blade::each('users.user', $users, 'user') !!}

The first parameter to @each is the view partial that should be included for each item in the list. The second and third parameters are the list itself and the alias for each item, respectively.

Conditional Includes

Blade enables conditional includes via the @includeWhen, @includeUnless, @includeFirst directives, which work as you might expect.

// Using @includeWhen
{!! Blade::includeWhen(auth()->user()->isAdmin(), 'admin.panel') !!}

// Using @includeUnless
{!! Blade::includeUnless(auth()->check(), 'guest.welcome') !!}

// Using @includeFirst
{!! Blade::includeFirst(['custom.panel', 'default.panel'], {'data' => $data}) !!}

With these, you can conditionally render sections of your views depending on logic within your application (e.g., only showing an admin panel to users who are admins).

Advanced Subview Inclusion

Subviews can also reflect complex structures by leveraging slots, components, and stacks. Blade’s @component directive allows for an even more fine-grained approach to creating reusable pieces of your UI:

{!! Blade::component('components.alert', 'alert') !!}
{$slot = 'Something happened!'}
{!! Blade::alert(['type' => 'warning']) !!}

Slots can be used within your components to insert content into predefined sections. By putting some of your HTML layout into stacks, you can push to them from your subviews:

@push('scripts')
<script src="/js/my_script.js"></script>
@endpush

Using stacks, you can maintain a clear boundary between layout definitions and content that should be rendered within these layouts.

Combining Multiple Subviews

An advanced usage scenario would involve nesting subviews, conditionally displaying them, and passing variables through multiple layers. Composing sophisticated templates often entails using all the features discussed above in conjunction with blade loops, conditionals, and even raw PHP.

{!! Blade::each('products.list_item', $products, 'product') !!}

This way of structuring views modularizes the view layer and keeps code clean and maintainable.

Conclusion

Use of subviews in Blade is crucial for writing well-structured, maintainable Laravel applications. Through this tutorial, you’ve learned how to include subviews, pass data to them, use them conditionally, and build more complex views. Happy coding!

Next Article: Laravel Blade: How to escape dangerous HTML & JavaScript

Previous Article: Laravel: How to conditionally render data with Blade

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array