Laravel View Components and Blade Complete Guide
Introduction
Laravel's view components provide a powerful way to build reusable UI elements. Whether you're creating buttons, modals, cards, or complex widgets, components help maintain clean architecture and code reusability in your Laravel applications.
Creating Components
Laravel makes it easy to create components using Artisan:
php artisan make:component Alert
This creates two files:
- app/View/Components/Alert.php - The component class
- resources/views/components/alert.blade.php - The view template
Component Classes
Define data and logic in the component class:
// app/View/Components/Alert.php
namespace App\View\Components;
use Illuminate\View\Component;
class Alert extends Component
{
public $type;
public $message;
public $dismissible;
public function __construct(
$type = 'info',
$message = '',
$dismissible = false
) {
$this->type = $type;
$this->message = $message;
$this->dismissible = $dismissible;
}
public function render()
{
return view('components.alert');
}
public function getTypeClass()
{
return match($this->type) {
'success' => 'bg-green-100 border-green-500 text-green-700',
'error' => 'bg-red-100 border-red-500 text-red-700',
'warning' => 'bg-yellow-100 border-yellow-500 text-yellow-700',
default => 'bg-blue-100 border-blue-500 text-blue-700',
};
}
}
Slots and Props
Use slots to pass content to components:
<!-- resources/views/components/alert.blade.php -->
<div class="border-l-4 p-4 {{ $getTypeClass() }}" role="alert">
<div class="flex justify-between items-center">
<div>
{{ $message }}
{{ $slot }}
</div>
@if($dismissible)
<button type="button" class="close" data-dismiss="alert">
×
</button>
@endif
</div>
</div>
Using the Component
<x-alert type="success" message="Operation successful!">
Your changes have been saved.
</x-alert>
Anonymous Components
Create simpler components without classes:
<!-- resources/views/components/button.blade.php -->
<button
{{ $attributes->merge(['class' => 'btn btn-primary']) }}
>
{{ $slot }}
</button>
<!-- Using anonymous component -->
<x-button type="submit" class="mt-4">
Save Changes
</x-button>
Best Practices
- Single responsibility - Each component should do one thing well
- Use props wisely - Keep component interfaces simple
- Leverage slots - Use named slots for flexible content
- Organize components - Group related components in folders
- Use attributes merge - Allow overriding default classes
Summary
View components and Blade templates in Laravel provide a powerful foundation for building reusable, maintainable UI elements. By following best practices, you can create a component library that speeds up development and ensures consistency across your application.
For more information, check out our other tutorials on Custom Helpers and Form Request Validation.