Within a Laravel Livewire component, I have a computed property (rather than a public property) for caching/db performance reasons.
Within a blade template, that computed property is bind-ed (bound) to a UI element (text area).
However when I update that UI element (by typing in the text area), I'm getting an error: Unable to set component data. Public property [$myobject] not found on component: [mycomponent]
.
I'm not sure why it can't find the computed property?
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Cache;
use App\Models\MyModel;
class MyComponent extends Component
{
public int $myobjectid = 0;
protected $listeners = [
...
];
protected $rules = [
'myobject.career' => 'nullable|string',
];
public function getMyobjectProperty()
{
// This is really retrieved from the Cache, but for simplicity...
return MyModel::find($this->myobjectid);
// This Model does have a property called 'career'
}
public function mount(): void
{
}
public function render() {
return view('livewire.mycomponent');
}
}
In my view (livewire/mycomponent.blade.php):
<div>
...
@dump($this->myobject) // works fine...
@dump($this->myobject->career) // also works fine...
...
<textarea wire:model.debounce.500ms="myobject.career" rows="5" class="textarea textarea-bordered"></textarea>
...
</div>
Dumping the $this->myobject
works fine, and shows it as an App\Models\MyModel
.
Can you not bind to a computed property?
You cannot bind to or update a computed property.
The computed properties are useful to fetch data to display, but since its a derived/computed expression, it's impossible to know how to update it.
Instead, bind the properties of the model you want to update to individual properties of the class, and then bind to those.
public $career;
protected $rules = [
'career' => 'nullable|string',
];
<textarea wire:model.debounce.500ms="career" rows="5" class="textarea textarea-bordered"></textarea>
Then you'll need some logic to actually save and update the record in the database.