Search code examples
phplaravellaravel-livewire

Livewire 3 Component Input [Text] Update to Parent Variable


I have a livewire sub component where it loads under form

Form -> Input

Controller Snippet

class ListingEdit extends Component
{
    public $title; => Need to update this one

Here is the blade file in the form where I call component.input.input

<div class="mb-3">
    @livewire('component.input.input', ['value' => $title], key($title))
    <x-input-error :messages="$errors->get('title')" class="mt-2" />
</div>

Here is Livewire Input Controller

<?php

namespace App\Livewire\Component\Input;

use Livewire\Component;

class Input extends Component
{
    public $value;
    public function render()
    {
        return view('livewire.component.input.input',['title' => $this->value]);
    }
}

Here is the blade file of component.input.input

<input wire:model.live="value" {{ $disabled ? 'disabled' : '' }} {!! $attributes->merge(['class' => 'w-full border border-gray-300 p-2 focus:border-gray-500 focus:ring-gray-500 rounded-md shadow-sm']) !!}>
{{ $title ?? 'as' }}

I was trying to use [Reactive] under child component but it went

Cannot mutate reactive prop [value] in component: [component.input.input]

I read the reactive can only be used to feed from parent -> child where I want to feed from child to parent


Solution

  • This situation seems suitable for using the Modelable functionality:

    The nested component called from the parent:

    <div class="mb-3">
       <x-livewire:component.input.input wire:model="title" :key="$title" />
    
        <!-- ...... -->
    

    The child Input class:

    namespace App\Livewire\Component\Input;
    
    use Livewire\Component;
    use Livewire\Attributes\Modelable;
    
    class Input extends Component
    {
        #[Modelable]
        public $title;
    
        // the render is implicit
    }
    
    

    In the Input blade:

    <input wire:model.live="title">
    

    Reference here