Search code examples
phplaraveleloquenttransactionseloquent-relationship

Laravel sync with database transactions


I'm creating an import excel in laravel using Maatwebsite\Excel. As for each row I have to multiple operations I'm using the onRow method with the default db transactions to avoid load partial data in case of error.

So, in this method I create a User and then associate it with the indicated roles (many to many relationship). Here is the code:

$user = User::firstOrCreate([
    'username' => $row['username'],
],[
    'name' => $row['name'],
    'surname' => $row['surname'],
    'email' => $row['email'],
]);

$user->roles()->sync(explode(',', $row['roles']));

But the method sync fails, as the transaction has not created a $user, so there's not any id to insert in the pivot table.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into `user_role` (`role_id`, `user_id`) values (1, ?))

I hope you can help me! Thank you


Solution

  • Thank you @Yannick Beuchat, your comment wasn't the solution but led me to the correct answer. The problem is that my model User extends the Pivot class instead of Model class. In Pivot class the property $incrementing is set to false. Adding this in model User solved the issue.

    public $incrementing = true;
    

    Thanks again!