In this tutorial i’ll guide, you will learn how to get the last insert id in Laravel.
1. Using Eloquent Save Method
When you create or update a model in Laravel, you can easily get the ID of the last inserted record by using the save()
method.
<?php
$user = new User();
$user->name = 'John Doe';
$user->email = 'johndoe@example.com';
$user->save();
$lastInsertId = $user->id;
2. Using Elogquent Create Method
<?php
$user = User::create(['name' => 'John Doe', 'email' => 'johndoe@example.com']);
$lastInsertId = $user->id;
3. Using DB Facade
<?php
$lastInsertId = User::insertGetId(['name' => 'John Doe', 'email' => 'johndoe@example.com']);
4. Using getPDO() Method
<?php
$user = DB::table('users')->insert(
[ 'name' => 'John Doe', 'email' => 'johndoe@example.com' ]
);
$userId = DB::getPdo()->lastInsertId();.
dd($userId);
That’s it for now. I hope this little tip helps you.