Hi,
Is there a proper way to implement DB transaction in a MorphTo model relationship? I am trying to fire a custom event when the model and it's morphTo relationship is saved to the DB.
Not sure what I'm doing is the proper way to do it, or if there is a better way of doing it.
public function save()
{
if( $this->offsetExists('addressModel')) {
DB::beginTransaction();
parent::save();
if (!$this->address()->save($this->addressModel)) {
throw new \Exception("The order's address relation was not created");
}
DB::commit();
$this->fireModelEvent('order_created');
} else {
parent::save();
}
}
public function addAddress(Address $address)
{
$this->addressModel = $address;
}
Is it working? That's the way I would go about it. One thing to note, you're missing a DB::rollback() call on failure which I think is necessary to call (just for safety's sake at least)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community