Create and Use Reusable Laravel Component Like Vue React Js

Hello artisan, in this example, i will show you, how you can create reusable component in Laravel using laravel component. In this laravel blade components tutorial, you will learn how to create and use laravel 8 blade components.

Components and slots provide similar benefits to sections, layouts, and includes like react js vue js component. However, some may find the mental model of components and slots easier to understand than react and vue component. There are two approaches to writing components: class based components and anonymous components.

I also discuss about  laravel components slot example. To create a class based component, We have to use the make:component Artisan command. Let's create a component:

php artisan make:component Alert

 

The make:component command will place the component in the App\View\Components directory. The make:component command will also create a view template for the component. The view will be placed in the resources/views/components directory.

Rendering Component

To display a component, you may use a Blade component tag within one of your Blade templates. Blade component tags start with the string x- followed by the kebab case name of the component class:

 

Passing Data to Laravel Component

You can pass data to the component like vue and react. You may pass data to Blade components using HTML attributes. Hard-coded, primitive values may be passed to the component using simple HTML attribute strings.

 

We must define the component's required data in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's render method:

App\View\Components\Alert.php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
  
    public $type;

    public $message;

    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    public function render()
    {
        return view('components.alert');
    }
}

 

When our component is rendered, We can display the contents of your component's public variables by echoing the variables by name:

resources/views/components/alert.blade.php

 

Slot 

We will often need to pass additional content to your component via "slots". Component slots are rendered by echoing the $slot variable.

 

We can pass content to the slot by injecting content into the component:

 

Read also: Some Artisan Commands to Speed Up Laravel Application

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.