How to Add Components in Laravel 9

How to Add Components in Laravel

x- indicates component and input indicates component name -<x-input />

We can reuse a code multiple times without repeatations.
Write the code as given below and start creating components.

<div class="container">
        <h1 class="text-center">Registration Form</h1>
        <form action="{{url('/')}}/register" method="post">
            @csrf
            @php
                $demo = 1;
            @endphp
            <x-input type="text" name="name" placeholder="Please enter your name" 
             label="Name" :demo="$demo"/>

            <x-input type="email" name="email" placeholder="Please enter your email" 
             label="Email"/>

            <x-input type="password" name="password" placeholder="Please enter your 
            password" label="Password"/>

            <x-input type="password" name="confirm_password" placeholder="Please 
             enter your confirm password" label="Confirm Password"/>

            <button class="btn btn-primary">Submit</button>
        </form>
    </div>

After that run this command -

php artisan make:component Input

in the vs code terminal or do it mannually.

After executing this command two folders and files will be created.

1. views>components>input.blade.php

2. apps>views>components>Input.php

Your component code will be in views>components>input.blade.php -

<div class="mb-3">
    <label for="{{$name}}" class="form-label">{{$label}}</label>
    <input type="{{$type}}" class="form-control" name="{{$name}}" id="{{$name}}" 
       aria-describedby="emailHelpId" placeholder="{{$placeholder}}">
    <span class="text-danger">
        {{$demo}}
      @error($name)
          {{$message}}
      @enderror
    </span>
</div>

And all the values fetch from apps>views>components>Input.php -

namespace App\View\Components;

use Illuminate\View\Component;

class Input extends Component
{
    public $type;
    public $label;
    public $name;
    public $placeholder;
    public $demo;

    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct($type, $label, $name, $placeholder, $demo=0)
    {
        $this->type = $type;
        $this->label = $label;
        $this->name = $name;
        $this->placeholder = $placeholder;
        $this->demo = $demo;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.input');
    }
}

Now you can try http://127.0.0.1:8000/register on brower if you have started your localhost. if not started then - follow these steps.

Comments