Hi Dev,
Today, we will show you how to add blade components in laravel 10. This article will give you simple example of how to add blade components in laravel 10. Let’s discuss how to add blade components in laravel 10. In this article, we will implement a how to add blade components in laravel 10.
What are Laravel blade components?
Laravel Blade components are reusable, self-contained building blocks for your views. They allow you to encapsulate UI elements, making your code cleaner, more maintainable, and promoting the concept of “Don’t Repeat Yourself” (DRY). Components are incredibly versatile and can represent anything from simple buttons to complex form elements.
Install the Laravel 10
composer create-project --prefer-dist laravel/laravel laravel-app cd laravel-app
Create a Blade Component
Now, generate blade component by running the command.
php artisan make:component Button cd laravel-app
“This command will create a new directory in your resources/views/components folder that will contain a blade view (button.blade.php) and the associated PHP class (button.php) within the views/components directory.
Define the Component Blade View
Navigate to the button.blade.php file located in the resources/views/components directory. Within this file, define the HTML structure and any necessary logic for your button component. For example
<button {{ $attributes->merge(['class' => 'bg-blue-500 text-white']) }}> {{ $slot }} </button>
We take advantage of the $attributes variable to merge any additional attributes provided to the component. The $slot variable represents the content inserted within the component when used in a view.
Use the Blade Component
Now that our component is defined, let’s include it in a view. Open any Blade view (for example, resources/views/welcome.blade.php) and include your component using the
<x-button> Click Me </x-button>
Reusable Components with Parameters
<x-button color="red"> Danger </x-button>
To accomplish this, access the Button.php class in the Views/Components directory and declare a public property called ‘color’.
<?php namespace App\View\Components; use Closure; use Illuminate\Contracts\View\View; use Illuminate\View\Component; class Button extends Component { public $color; /** * Create a new component instance. */ public function __construct($color = 'blue') { $this->color = $color; } /** * Get the view / contents that represent the component. */ public function render(): View|Closure|string { return view('components.button'); } }
use the $color property inside the button.blade.php view.
<button {{ $attributes->merge(['class' => 'bg-' . $color . ' text-white']) }}> {{ $slot }} </button>
I hope it will assist you…