0
0
Laravelframework~5 mins

Components and slots in Laravel

Choose your learning style9 modes available
Introduction

Components and slots help you build reusable parts in your web pages. They keep your code clean and easy to manage.

You want to reuse a button style across many pages.
You need to create a card layout that changes content but keeps the same design.
You want to pass different content inside a common wrapper.
You want to separate your page into smaller, manageable pieces.
You want to avoid repeating HTML code in multiple places.
Syntax
Laravel
{{-- Define a component --}}
<x-component-name>
    {{-- Slot content here --}}
</x-component-name>

{{-- In component blade file --}}
<div>
    {{ $slot }}
</div>
Use to include a component in your blade view.
Inside the component blade file, use {{ $slot }} to show the passed content.
Examples
This passes the text inside the alert component's slot.
Laravel
<x-alert>
    This is an alert message.
</x-alert>
This is the alert component showing the slot content inside a div with class alert.
Laravel
<!-- resources/views/components/alert.blade.php -->
<div class="alert">
    {{ $slot }}
</div>
Using named slots lets you pass different parts like title and body separately.
Laravel
<x-card>
    <x-slot name="title">Card Title</x-slot>
    This is the card body content.
</x-card>
The card component uses a named slot 'title' and the default slot for body content.
Laravel
<!-- resources/views/components/card.blade.php -->
<div class="card">
    <h2>{{ $title }}</h2>
    <div>{{ $slot }}</div>
</div>
Sample Program

This example creates a button component that wraps any text passed inside it. The welcome view uses the button component with the text 'Click me'.

Laravel
<!-- resources/views/components/button.blade.php -->
<button class="btn">
    {{ $slot }}
</button>

<!-- resources/views/welcome.blade.php -->
<x-button>
    Click me
</x-button>
OutputSuccess
Important Notes

Slots let you insert any HTML or text inside components.

Named slots help organize multiple content areas inside one component.

Components improve code reuse and make your views cleaner.

Summary

Components are reusable pieces of UI in Laravel Blade.

Slots let you pass content into components.

Use named slots for multiple content sections inside a component.