Search code examples
laravellaravel-livewire

Laravel Livewire Component not reading simple html parameters


Just started using Laravel Livewire and I have a problem with passing parameters to a livewire component.

Home.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
        @livewireStyles
    </head>
    <body class="antialiased p-10">
        
        <livewire:forms.input type="text" name="Test" />

        @livewireScripts
    </body>
</html>

Component

<div class="FormsInput">
    @isset($label)
    <label for="{{ $name }}">{{ $label }}</label>
    @endisset
    <div class="">
        <input wire:model="{{ $name }}" type="{{ $type }}" name="{{ $name }}" id="{{ $name }}" placeholder="{{ $placeholder }}">
    </div>
    @isset($helper)
    <div class="">
        {{ $label }}
    </div>
    @endisset
    <div class="">
        {{ $error }}
    </div>
</div>

Http/Livewire/Forms/Input

<?php

namespace App\Http\Livewire\Forms;

use Livewire\Component;

class Input extends Component
{
    public function render()
    {
        return view('livewire.forms.input');
    }
}

This is the error that I get:

ErrorException
Undefined variable $name

enter image description here


Solution

  • To fix this error you have to do two things:

    1. Add name property to your component because Livewire components store and track data as public properties on the component class.
    
    class Input extends Component
    {
       public string $name;
    
         ...
    }
    
    1. Use property name on wire:model without '$'
    <input wire:model="name" ... />
    

    You can find data binding on Livewire docs at this Link.