how to use component in laravel - deesoft service

how to use component in laravel

Deepak Tailor Image
Deepak Tailor - Jan 26 2023
how to use component in laravel

Components are small pieces of code. Which we can use many times in blade file. Due to which the code in the blade file is reduced, it is easy to read the code. 2 files are generated in the component, a class file and a blade file for the view.

How to Create new component in laravel

A command is given to create a component in Laravel. With whose help we can create components.

A file is created in the app / view / component folder. In this we write the logic related code and a file is created in resource / views / component folder. In this we keep the design code.

php artisan make:component Component Name
php artisan make:component Input
php artisan make:component ProductCard
How to use component in blade file

Let's start with x to use the component in the blade file. As

<x-input />
<x-simple-button />
<x-outline-button />
<x-product-card />
<x-footer-list />
Pass static data in component file

We can also pass static data in the component. As

<!-- generate dynamic input fields with using component -->
<x-input type="text" name="first_name" />
<x-input type="text" name="last_name" />
<x-input type="number" name="mobile_no" />
<x-input type="email" name="email" />

<!-- generate dynamic button with using component -->
<x-simple-button title="Submit" />
<x-simple-button title="Login" />
<x-simple-button title="Register" />
Pass dynamic data / variables in component file

We can also pass static and dynamic variables and data to the component. This is a great feature of Laravel. Due to which the readability of the code increases.

@foreach($input_array as $single)
    <x-input type="text" :name="$single" />
@endforeach

@foreach($button_list_array as $single)
    <x-simple-button :title="$single" />
@endforeach
Get argument in component class file

When we pass some arguments to the component, then all those arguments are received in the constructor of the component's class file.

class Input extends Component
{
    public $type;
    public $name;
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct($type, $name)
    {
        $this->type = $type;
        $this->name = $name;
    }
}

Set variables in component view file

<div>
    <input type="{{ $type }}" name="{{ $name }}" class="form-control" />
</div>
Why use component in laravel

When we make a large project on Laravel, then the length of the code goes a lot in it. So we use component to shorten the code. Due to which the length of the code is reduced.

Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry (PHP, Nodejs, flutter) for the last 5 years. For professional and customize web development & app development, you can send inquiry on our email.
----
You can contact him at deepaktailor10@yahoo.in