0
0
LaravelHow-ToBeginner · 3 min read

How to Use @slot in Blade Templates in Laravel

In Laravel Blade, use @slot inside a @component block to define named sections that the component can display. This allows you to pass multiple pieces of content to a component by naming each slot with @slot('name') and ending it with @endslot.
📐

Syntax

The @slot directive is used inside a @component block to define a named section of content. You write @slot('slotName') to start the slot, then add the content, and close it with @endslot.

This lets the component access the content by the slot name.

blade
@component('components.alert')
    @slot('title')
        Warning!
    @endslot

    This is the alert message.
@endcomponent
💻

Example

This example shows a Blade component named alert that uses a @slot('title') to receive a title, and the main content is the alert message.

blade
{{-- resources/views/components/alert.blade.php --}}
<div style="border:1px solid red; padding:10px;">
    <strong>{{ $title }}</strong>
    <p>{{ $slot }}</p>
</div>

{{-- Usage in a Blade view --}}
@component('components.alert')
    @slot('title')
        Warning!
    @endslot

    This is the alert message.
@endcomponent
Output
<div style="border:1px solid red; padding:10px;"> <strong>Warning!</strong> <p>This is the alert message.</p> </div>
⚠️

Common Pitfalls

  • Forgetting to close a slot with @endslot causes errors or unexpected output.
  • Using @slot outside of a @component block will not work.
  • Not matching the slot name in the component and usage leads to empty content.
blade
{{-- Wrong: Missing @endslot --}}
@component('components.alert')
    @slot('title')
        Warning!
    {{-- Missing @endslot here --}}

    This is the alert message.
@endcomponent

{{-- Right: --}}
@component('components.alert')
    @slot('title')
        Warning!
    @endslot

    This is the alert message.
@endcomponent
📊

Quick Reference

@slot lets you name a section of content inside a @component. Use @slot('name') to start and @endslot to end. Access the slot in the component with {{ $name }}. The default unnamed content is accessed with {{ $slot }}.

DirectivePurposeUsage Example
@componentStart a component block@component('components.alert')
@slot('name')Define a named slot@slot('title') ... @endslot
@endslotEnd a named slotUsed after slot content
@endcomponentEnd the component block@endcomponent
$slotDefault unnamed slot contentUsed inside component to show main content
$nameNamed slot contentUsed inside component to show named slot

Key Takeaways

Use @slot inside @component to pass named content sections to Blade components.
Always close @slot with @endslot to avoid errors.
Access named slots in the component with variables matching the slot names.
The default slot content is accessed with $slot in the component.
Slots only work inside @component blocks, not standalone.