Laravel Blade Components
Laravel Blade Components: Tips & Tricks
Laravel Blade Components: Tips & Tricks
Tip: Use Anonymous Components for Simple UI
{{-- resources/views/components/alert.blade.php --}}
<div class="alert alert-{{ $type ?? 'info' }}">
{{ $slot }}
</div>
{{-- Usage --}}
<x-alert type="danger">Something went wrong!</x-alert>
No PHP class needed.
Gotcha: Component Attribute Bag
If you pass attributes that aren't defined as props, they go to $attributes:
{{-- component --}}
<button {{ $attributes->merge(['class' => 'btn']) }}>
{{ $slot }}
</button>
{{-- usage --}}
<x-button class="btn-primary" id="submit">Click</x-button>
The class merges: class="btn btn-primary".
Tip: Named Slots for Complex Components
<x-card>
<x-slot name="header">
<h2>{{ $title }}</h2>
</x-slot>
<p>{{ $slot }}</p>
</x-card>
Gotcha: Components Resolve via Container
Class-based components are resolved through the service container. You can inject dependencies:
public function __construct(protected SettingsService $settings) {}
Tip: Use @props for Default Values
@props(['type' => 'info', 'dismissible' => false])
<div class="alert alert-{{ $type }}">
@if($dismissible)
<button>×</button>
@endif
{{ $slot }}
</div>
Tip: Inline Components for Simple Logic
class Alert extends Component
{
public function render(): View
{
return <<<'blade'
<div class="alert alert-{{ $type }}">{{ $slot }}</div>
blade;
}
}
Gotcha: Component Namespace
Components in resources/views/components auto-register. Subdirectories use dot notation:
<x-forms.input /> {{-- resources/views/components/forms/input.blade.php --}}
Tip: Use route:cache Carefully
php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.
Tip: Model APP_KEY Rotation
Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.
Gotcha: Local Scope Leaks
Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.
Senior Insight
The Laravel ecosystem moves fast, and keeping up with every new first-party package can feel overwhelming. I've found that mastering the core — the container, Eloquent, queues, and the HTTP layer — pays far more dividends than chasing every new release. Architecture and debugging skills transcend framework versions. When I mentor developers, I focus on understanding the 'why' behind Laravel's design choices rather than memorizing syntax. The framework changes; the principles don't.
Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)