11 months ago

Using Transactions in Laravel User::Create for setting User Role

Posted 11 months ago by repulsor

What I am trying to do is to set a user role immediately after user creation, and tie them together in a transaction so it rollbacks incase of any issues because it is very crucial.

So far I have reached here trying to get this done.

 protected function create(array $data)
    return DB::transaction(function () use ($data) {
    $NewUser = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'phone' => $data['phone'],
        'password' => Hash::make($data['password']),

    $row_id = $this->create($data)->id;
    $UserRole = UserRole::create([
        'user_id'=> $row_id,
        'role_id' => 1,


The code has obvious issues,doesnt work, and I would need a little bit help to get it right.

This returns Integrity constraint violation: 1062 Duplicate entry for the email field but THE ROW IS INSERTED IN THE TABLE.

It will just work fine if I remove extra code and return User::create as in default.

Any help?

Please sign in or create an account to participate in this conversation.