patternphplaravelTip
Blade Components: Anonymous vs Class-Based and Slot Patterns
Viewed 0 times
bladecomponentslotpropsattributesanonymous componentx-componentmake:component
Problem
Blade @include directives pass data via compact() which is fragile and does not communicate the expected interface. Reusable UI elements lack clear prop contracts.
Solution
Prefer class-based components (php artisan make:component) for components with significant logic or validation. Use anonymous components (resources/views/components/) for pure HTML. Define props with public constructor parameters or the @props directive. Use named slots for complex content injection.
Why
Class-based components have a typed PHP class that clearly documents expected props. The component tag syntax (x-component-name) is self-documenting. Slots allow consumers to inject arbitrary HTML into designated regions.
Gotchas
- Attributes not listed in props are collected in $attributes and should be merged onto the root element with {{ $attributes }}
- Anonymous components use @props(['name' => 'default']) at the top of the template
- Component discovery scans resources/views/components automatically—no registration needed
- Use $attributes->merge(['class' => 'base-class']) to safely combine caller-provided classes
Code Snippets
Class-based component with props
// app/View/Components/Alert.php
class Alert extends Component
{
public function __construct(
public string $type = 'info',
public string $message = ''
) {}
public function render(): View
{
return view('components.alert');
}
}
{{-- resources/views/components/alert.blade.php --}}
<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
{{ $message }}
{{ $slot }}
</div>Revisions (0)
No revisions yet.