I have a simple transaction structure and a belongsToMany-relationship between 2 models user and sponsoring. I found out that the relationship data are not saved in the pivot table, when I wrap it inside a transaction. Without a transaction it works fine. Is this a zero day bug in laravel (framework v8.40) or does it work somehow different?
My models are defined like this:
class Sponsoring extends Model
{
use HasFactory;
use SoftDeletes;
public function users()
{
return $this->belongsToMany(User::class, 'user_sponsorings');
}
// ...
}
class User extends Authenticatable implements HasLocalePreference
{
use SoftDeletes;
use HasFactory;
use Notifiable;
public function sponsorings()
{
return $this->belongsToMany(Sponsoring::class, 'user_sponsorings');
}
// ...
}
My code looks like:
//DB::beginTransaction();
try {
$sponsoring = new Sponsoring();
// ...
$sponsoring->save();
$userIds = [ Auth::user()->id ];
// ...
$sponsoring->users()->sync($userIds);
} catch (\Exception $ex) {
//DB::rollBack();
throw new Error('could not save sponsoring: ' . $ex->getMessage());
}
//DB::commit();