Search code examples
phplaravellaravel-livewire

cannot access livewire form object property


I tried to access livewire form object property, but it always return an error like so:

Undefined variable $employee

My livewire EditEmployee class :

public EmployeeForm $form;

public function mount(Employee $employee)
{
    $this->form->setEmployee($employee);
}

public function save()
{
    $this->form->update();
    
    flash('employee data has been updated', 'success');
    
    return redirect()->route('employee');
}

Livewire EmployeeForm class :

public ?Employee $employee;

#[Rule('required')]
public string $status = '';

#[Rule('required')]
public string $name = '';

#[Rule('string')]
public string $address = '';

public function setEmployee(Employee $employee)
{
    $this->employee = $employee;
    $this->name = $employee->name;
    $this->address = $employee->address;
}

blade :

<input class="form-control" id="name" type="text" placeholder="Name" name="name" wire:model="form.name"/>
<label for="name">{{ $employee->name }}</label>
@error('form.name')
    <small class="text-danger d-block mt-1">{{ $message }}</small>
@enderror

I wonder if the $employee property from the Form property also can be accessed using the Livewire component class (in this case EditEmployee class) ?


Solution

  • To print the $employee property from the $form object, from the parent view, you'll need to specify the form property.

    {{ $this->form->employee->name }}