Blade Component In Laravel
Hi readers, If you are also a Laravelers that means you do write code in Laravel then you may know about the Blade Templating Engine. So, Blade is th...
Hi readers, If you are also a Laravelers that means you do write code in Laravel then you may know about the Blade Templating Engine. So, Blade is the default templating engine in Laravel. In Blade, we get the "components" feature from Laravel. It offers a simple yet powerful way of creating dynamic and reusable UI components using templates.
Creating a Basic Blade Component
To create a basic Blade component, you need to follow these simple steps:
- Create a new directory called
components
inside theresources/views
directory of your Laravel application. - Inside the
components
directory, create a new blade file with a.blade.php
extension, such asbutton.blade.php
. - In the
button.blade.php
file, define the HTML and any necessary logic for your component. For example:
<button {{ $attributes->merge(['class' => 'bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded']) }}>
{{ $slot }}
</button>
Here, we have created a simple button component that includes some CSS classes and a slot for the button text.
- To use the component in a view, you can include it using the
x
prefix. For example:
<x-button>
Click me!
</x-button>
This will output a button element with the text "Click me!".
Creating an Advanced Blade Component In Laravel
To create an advanced Blade component, you can follow these steps:
- Inside the
components
directory, create a new blade file with a.blade.php
extension, such asalert.blade.php
. - In the
alert.blade.php
file, define the HTML and any necessary logic for your component. For example:
@props(['type' => 'info', 'message'])
<div {{ $attributes->merge(['class' => 'alert alert-' . $type]) }}>
{{ $message }}
</div>
Here, we have created an advanced alert component that includes a dynamic alert-{type}
class based on the $type
variable passed to the component. The component also includes a slot for the alert message.
Note the @props
directive at the top of the component file. This directive defines any variables that can be passed to the component when it is used. In this case, the type
and message
variables are defined with default values.
- To use the component in a view, you can include it using the
x
prefix and pass any necessary variables. For example:
<x-alert type="success" message="Your changes have been saved." />
Related: Resource Routes In Laravel
In conclusion, Blade components are a powerful way of creating reusable UI elements in Laravel. By following the steps mentioned above, you can easily create both basic and advanced Blade components and use them in your Laravel application.