DEV Community

Cover image for How to used Component in Laravel
Zaw Zaw Win
Zaw Zaw Win

Posted on

How to used Component in Laravel

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
Enter fullscreen mode Exit fullscreen mode

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


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(
    ) {

        $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');

Enter fullscreen mode Exit fullscreen mode

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.

    <label for="{{ $name }}">{{$label}}</label>
    <input type="{{ $type }}" 
           class="form-control @error('email') is-invalid @enderror" 
           id="{{ $name }}" name="{{ $name }}"
          placeholder="{{ $placeholder }}">

          <div class="invalid-feedback">
            {{ $message->first() }}

Enter fullscreen mode Exit fullscreen mode

Step 4

Go any blade files inside your can used this components like below

  <x-forms.input-text type="text"
                      placeholder="Please Enter your name"

Enter fullscreen mode Exit fullscreen mode

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)