==== # Laravel Blade Components ## Introduction Laravel Blade Components are a powerful feature in Laravel's templating engine that allows you to create reusable UI elements with isolated logic. They were significantly enhanced in Laravel 7 and continue to be a cornerstone of Laravel's front-end ecosystem. ## Understanding Blade Components Blade Components allow you to extract reusable parts of your interface into a single file with its own logic, properties, and slots. Think of them as custom HTML elements that you can reuse across your application. ## Practical Example: Creating an Alert Component Let's create a reusable alert component that can display different types of notifications (success, error, warning) throughout our application. ### Step 1: Generate the component ```bash php artisan make:component Alert ``` This creates two files: - `app/View/Components/Alert.php` - The component class - `resources/views/components/alert.blade.php` - The component template ### Step 2: Define the component class ```php // app/View/Components/Alert.php namespace App\View\Components; use Illuminate\View\Component; class Alert extends Component { public $type; public $message; /** * Create a new component instance. * * @param string $type * @param string $message * @return void */ public function __construct($type = 'info', $message = null) { $this->type = $type; $this->message = $message; } /** * Get the view / contents that represent the component. * * @return \Illuminate\View\View|\Closure|string */ public function render() { return view('components.alert'); } /** * Get the appropriate CSS class based on alert type. * * @return string */ public function typeClass() { return [ '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', 'info' => 'bg-blue-100 border-blue-500 text-blue-700', ][$this->type] ?? 'bg-blue-100 border-blue-500 text-blue-700'; } } ``` ### Step 3: Create the component template ```blade {{-- resources/views/components/alert.blade.php --}}
{{ $message }}
@else {{ $slot }} @endifThere was an error processing your request.
Please try again later.