Wonka
Wonka

Reputation: 8674

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?

Upvotes: 4

Views: 4163

Answers (3)

Stefan
Stefan

Reputation: 832

$id = DB::table('table')->insert( $data )->lastInsertId();

Upvotes: 0

Zayn Ali
Zayn Ali

Reputation: 4915

You can also use your User model to create a new user. In return, it'll give you the user object to work with.

$user = User::create([
    'email'     => '[email protected]',
    'password'  => bcrypt('your-password')
]);

dd($user->id);

Upvotes: 1

Pawel Bieszczad
Pawel Bieszczad

Reputation: 13325

According to the documentation you should be using the insertGetId method

$newUserId= DB::table('users')->insertGetId([
    'email' => $email,
    'password' => $password
]);

Upvotes: 8

Related Questions