Support the ongoing development of Laravel.io →
Database Eloquent

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;
} 

Last updated 3 years ago.
0

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)

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

moleculezz moleculezz Joined 18 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.