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 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:

  1. Create a new directory called components inside the resources/views directory of your Laravel application.
  2. Inside the components directory, create a new blade file with a .blade.php extension, such as button.blade.php.
  3. 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.

  1. 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:

  1. Inside the components directory, create a new blade file with a .blade.php extension, such as alert.blade.php.
  2. 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.

  1. 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.

Leave a Comment