I’m a bit lost on the best method to update Eloquent Models with Livewire after upgrading from 0.4.*.
For example; this is how I used to do it (I removed unrelated code):
Class Person extends Component
{
protected $person = null;
public $name, $emailaddress;
public function update(){
// Triggered on wire:click
$this->validate([
'name' => 'required',
'emailaddress' => 'required|email',
]);
$this->person->name = $this->name;
$this->person->emailaddress = $this->emailaddress;
$this->person->save();
// The form is in a modal component
$this->emit('close-modal');
}
public function mount($person_id){
$this->person = \App\Person::find($person_id);
$this->name = $this->person->name;
$this->emailaddress = $this->person->emailaddress;
}
public function render(){
return view('person.edit');
}
}
Simplified blade view:
<input type="text" wire:model="name">
<input type="text" wire:model="emailaddress">
<button type="button" wire:click="update">Save</button>
Since 0.5.* we should be able to use Eloquent models in public properties, but does this simplify such a component as well? I somehow expected it to work like this, but it doesn’t:
Class Person extends Component
{
public $person;
public function update(){
// Triggered on wire:click
$this->validate([
'person.name' => 'required',
'person.emailaddress' => 'required|email',
]);
$this->person->save();
// The form is in a modal component
$this->emit('close-modal');
}
public function mount($person_id){
$this->person = \App\Person::find($person_id);
}
public function render(){
return view('person.edit');
}
}
Simplified blade view:
<input type="text" wire:model="person.name">
<input type="text" wire:model="person.emailaddress">
<button type="button" wire:click="update">Save</button>
Am I right that the way to go is as follows? Or can it be simplified? Which would especially be nice for models lots of attributes / large forms?
Class Person extends Component
{
public $person, $name, $emailaddress;
public function update(){
// Triggered on wire:click
$this->validate([
'name' => 'required',
'emailaddress' => 'required|email',
]);
$this->person->name = $this->name;
$this->person->emailaddress = $this->emailaddress;
$this->person->save();
// The form is in a modal component
$this->emit('close-modal');
}
public function mount($person_id){
$this->person = \App\Person::find($person_id);
$this->fill($this->person);
}
public function render(){
return view('person.edit');
}
}
Thanks!