@component/@slot vs @include

What's the differences between these Blade methods?

Many developers don't see any difference between using @component and @include methods when working with Blade templates.

Let's look at each method by solving simple examples.

First situation. Display static data

There is a file copyright.blade.php, which contains some text:

<div class="copyright">
    Roman Sarvarov © {{ now()->year }}
</div>

Solution using @include

@include('copyright')

Solution using @component

@component('copyright')
@endcomponent

As a result, the same text will be displayed on the screen: Roman Sarvarov © 2020, however, in this case, it is preferable to use @include, because we don't need to pass any data to the called file.

Second situation. Display data from passed variable

There is a file alert.blade.php, what display the message passed through the methods in question is output.

Solution using @include

<div class="alert alert-primary" role="alert">
    {!! $message !!}
</div>
@include('alert', ['message' => '<strong>Hello,</strong> world!'])

Solution using @component

<div class="alert alert-primary" role="alert">
    {!! $slot !!}
</div>
@component('alert')
    <strong>Hello,</strong> world!
@endcomponent

Third situation. Display data from multiple variables

As in the previous example, there is an alert.blade.php where the message is displayed, but now there is one more variable $title.

Solution using @include

<div class="alert alert-primary" role="alert">
    <div class="alert-title">{!! $title !!}</div>
 
    {!! $message !!}
</div>
@include('alert', [
    'title' => 'Hey!',
    'message' => '<strong>Hello,</strong> world!',
])

Solution using @component

<div class="alert alert-primary" role="alert">
    <div class="alert-title">{!! $title !!}</div>
 
    {!! $slot !!}
</div>
@component('alert')
    @slot('title', 'Hey!')
 
    <strong>Hello,</strong> world!
@endcomponent

Conclusions

If you look at it, there is no big difference between these two methods. However, I found one significant difference between these methods:

In other cases, there are no functional differences - only improvements in code readability in certain situations.

Let's draw conclusions.

Use @include when:

  • You just need to display the contents of the file without passing any variables
  • There are not many variables (1-2) and you like use @include more
  • Variables do not contain HTML and Blade syntax

In all other cases, use @component and @slot.

Comments

Spelling error report

The following text will be sent to our editors: