You can have multiple models as public properties on the Component; and you can bind form input and validation rules appropriate to each model using the dot syntax.
"Laravel" way to save to multiple models
Hello, first time posting here. I'm about 2 months into learning Laravel, currently developing a Livewire app as a learning project. The base project I started with uses the (Eloquent) Model->save() method/event to update the app page. Here's that code (in app/Http/Livewire/Project.php component):
public function save()
{
$this->validate();
$this->editing->save();
$this->showEditModal = false;
}
My issue is I'm saving to multiple models (database tables), so some of my form variables need to go to another model. If I try to use the save method above, Eloquent complains that some of the form variables do not have matching database columns. The FirstOrNew and FirstOrCreate methods both allow me to correct for that issue, but then I (*believe*) I have to lose the $this->editing model binding and the event/update of the app page doesn't happen. I've hacked together a working solution, which is this:
public function save()
{
$this->validate();
// clear the table of old selections first and then save all new selected options
ProjectTeam::where('project_id', $this->editing->id)->delete();
foreach ($this->editing->teams AS $id) {
ProjectTeam::create([
'project_id' => $this->editing->id,
'team_id' => $id
]);
}
unset($this->editing->teams);
$this->editing->save();
$this->showEditModal = false;
}
It works, but it doesn't look great. Unsetting attributes seems hacky; there has to be a way(s) Laravel would handle the situation, but a few days of scouring the internet hasn't shown me any solution. I'm also looking to save the user_id of the creator of any records, so a one-time injection of that attribute when it's saving a new record. Easy to do with FirstOrNew and FirstOrCreate, but I haven't been able to incorporate that logic using save(). Whenever I try to set it prior to saving, I get an error message saying something like "injecting attribute to the overloaded model has no effect."
Can anybody show me how this would optimally work in Laravel/Livewire? It's probably something simple, but I have been throwing spaghetti at the wall for days with no luck.
Thanks! jake
Please or to participate in this conversation.