WHY?? to use component?
Ans : Using components that help use clean code and we can separate reusable inside your components and use anywhere from your blade file.
There are two types of components in Laravel first class base component can pass data from from blade files and other one also called anonymous component that don't need to pass data directly using in your blade file.Okay ??? Don't worry I am going to explain you step by step.
Step 1
You need to generate a component using artisan commands line
php artisan make:component Forms/InputText
Then you will get two file one is inside
app\View\Components\Forms\InputText.php
and other resources\views\components\forms\input-text.blade.php
.
Step 2
Go to InputText.php folder
<?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class InputText extends Component
{
public string $type;
public string $label;
public string $name;
public string $placeholder;
/**
* Create a new component instance.
*/
public function __construct(
$type,
$label,
$name,
$placeholder
) {
$thsis->type = $type;
$this->label = $label;
$this->name = $name;
$this->placeholder = $placeholder;
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.forms.input-text');
}
}
This above code is for declare some variable that we will pass from blade components
Step 3
Go to forms\input-text.blade.php and used used the variables that you used in the InputText class.
<div>
<label for="{{ $name }}">{{$label}}</label>
<input type="{{ $type }}"
class="form-control @error('email') is-invalid @enderror"
id="{{ $name }}" name="{{ $name }}"
placeholder="{{ $placeholder }}">
@error($name)
<div class="invalid-feedback">
{{ $message->first() }}
</div>
@enderror
</div>
Step 4
Go any blade files inside your can used this components like below
<x-forms.input-text type="text"
label="Name"
name="name"
placeholder="Please Enter your name"
/>
The InputText
component allows you to create input text fields. When using this component, you can pass variables by using the name
attribute inside :name="$name"
.
Thank for reading this articles if you have any questions or any suggestions free feel to comments down @harom284
Top comments (0)