Laravel Blade – Advantage of @slot/@component vs @include?

Solution:

There are two key differences.

1. Variable scope

As described in @DavidHyogo’s answer, a component only sees variables explicitly passed to it. So you have to give it all variables like so…

@component('my-component', ['foo' => 'bar', 'etc' => 'etc'])

Whereas an include will adopt all variables from the global/current scope by default – unless you define an explicit set of variables to pass it, which then becomes local scope again.

{{-- This include will see all variables from the global/current scope --}}
@include('my-component')

{{-- This include will only see the variables explicitly passed in --}}
@include('my-component', ['foo' => 'bar', 'etc' => 'etc']) 

2. Component’s {{ $slot }} vs include’s {{ $var }}

When using a {{ $slot }} in a component, you can give it blade syntax code e.g…

{{-- alert.blade.php --}}
<div class="alert">{{ $slot }}</div>

@component('alert')
    <div>Hello {{ $name }} @include('welcome-message')</div>
@endcomponent

Note how the slot will receive html AND blade syntax code and just deal with it.

This is not possible with includes because you can only pass variables into includes…

{{-- alert.blade.php --}}
<div class="alert">{{ $slot }}</div>

@include('alert', ['slot' => "I CAN'T PASS IN BLADE SYNTAX HERE!"])

It could be done in a more hacky way by grabbing a fresh view() helper and passing it some variables to compile the output we want to pass into the slot, but this is what components are for.