Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Get newly inserted id in transaction?

So I am running a transaction that should create a user, and fire off an event to do additional things with the new user id, including creating a settings table where the foreign key user_id in the settings table is the newly created user_id (providing the transaction works of course).

Here is what I have so far:

DB::beginTransaction();

try {
    DB::table('users')->insert([
              'email' => $email,
              'password' => $password
    ]);

    event(new UserWasStored($newUserId)); // How do I get the $newUserId?
}
catch(\Exception $e) {
    DB::rollback();
}

DB::commit();

How can I get the $newUserId passed to the event within the transaction?

like image 650
Wonka Avatar asked Jan 06 '23 13:01

Wonka


1 Answers

According to the documentation you should be using the insertGetId method

$newUserId= DB::table('users')->insertGetId([
    'email' => $email,
    'password' => $password
]);
like image 71
Pawel Bieszczad Avatar answered Jan 31 '23 08:01

Pawel Bieszczad