4

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();

realphil86
  • 41
  • 1
  • what is the response youre getting? – JEJ Aug 04 '21 at 10:10
  • Given that Laravel is currently at 8.51 then try reproducing it on the latest build – apokryfos Aug 04 '21 at 10:11
  • @apokryfos as I could see, it is also in the latest laravel framework version 8.51. – realphil86 Aug 04 '21 at 12:54
  • @JEJ there is not error response. Everything seems to work fine, but inside transactions the relationship data are just not stored to db (or rejected)... :-( It seems to be an error with the DB::commit method and relationships. – realphil86 Aug 04 '21 at 12:57
  • somehow it works when you wrap the transaction inside return DB::transaction(function() { return $sponsoring; }); instead of using DB:startTransaction and commit ... seems to be a bug with transaction levels... – realphil86 Aug 04 '21 at 16:13

0 Answers0