Here is my code
$users = DB::table('users')->insert(array(
'email_id' => $email_id,
'name' => $name,
));
$lastInsertedID = $users->lastInsertId();
return $lastInsertedID;
I want to get last inserted id for particular record. I have tried using Eloquent ORM. but it didn't work.
Any help would be grateful.
Thank You.
Use insertGetId()
$id = DB::table('users')-> insertGetId(array(
'email_id' => $email_id,
'name' => $name,
));
Here are the following methods to get last inserted id
$user = new User();
$user->name = "Test";
$user->save();
dd($user->id);
$user = User::create(['name' => 'Test']);
dd($user->id);
In this method Primary Key must me id
. If its other then id
for example some_id
then this method will throw exception.
$id = DB::table('users')->insertGetId(['name' => 'Test']);
dd($id);
This method is usefull if you are using DB Facade and have Custom Primary Key like some_id
.
DB::table('users')->insert(['name' => 'Test']);
dd(DB::getPdo()->lastInsertId());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With