0
0
LaravelHow-ToBeginner · 3 min read

How to Use @component in Blade Templates in Laravel

Use the @component directive in Blade to include a reusable component view and pass data or slots to it. Wrap the component content between @component('view.name') and @endcomponent tags to render the component with optional slots.
📐

Syntax

The @component directive starts a component block by specifying the component view name. You can pass an array of data as the second argument. Inside the block, you can define slots using @slot. Close the block with @endcomponent.

  • @component('view.name', ['data' => $value]): Starts the component and passes data.
  • @slot('slotName'): Defines a named slot inside the component.
  • @endcomponent: Ends the component block.
blade
@component('components.alert', ['type' => 'danger'])
    @slot('title')
        Error!
    @endslot
    Something went wrong.
@endcomponent
💻

Example

This example shows how to use @component to include an alert box component with a title slot and a message. The component view uses the passed type and title slot to render styled content.

blade
// resources/views/components/alert.blade.php
<div class="alert alert-{{ $type }}">
    <strong>{{ $title }}</strong>
    <div>{{ $slot }}</div>
</div>

// usage in a Blade view
@component('components.alert', ['type' => 'success'])
    @slot('title')
        Success!
    @endslot
    Your operation completed successfully.
@endcomponent
Output
<div class="alert alert-success"> <strong>Success!</strong> <div>Your operation completed successfully.</div> </div>
⚠️

Common Pitfalls

  • Forgetting to close @component with @endcomponent causes rendering errors.
  • Not passing required data to the component view leads to undefined variable errors.
  • Using @slot outside @component block is invalid.
  • Confusing @component with Blade components introduced in Laravel 7+ which use <x-component /> syntax.
blade
@component('components.alert')
    @slot('title')
        Warning!
    @endslot
    This will fail if you forget @endcomponent
// Correct usage:
@endcomponent
📊

Quick Reference

DirectivePurpose
@component('view', [data])Start a component block and pass data
@slot('name')Define a named slot inside the component
@endcomponentEnd the component block
$slotDefault slot content inside the component view
$variableData passed to the component view

Key Takeaways

Use @component with a view name and optional data array to include reusable Blade components.
Define slots inside @component blocks using @slot to customize parts of the component.
Always close @component blocks with @endcomponent to avoid errors.
Remember @component is different from Laravel's newer Blade components using syntax.
Pass all required data to the component view to prevent undefined variable errors.