In Laravel, after inserting data into a database table, you might need to retrieve the last insert ID after creating the record. This ID is essential for various tasks, like redirecting users to the newly created resource or performing further operations.
This blog post will guide you through several methods to get the last insert ID, by using Eloquent models, the DB facade, or by directly accessing the PDO instance. Let’s explore the various approaches!
Method 1: Retrieving Insert ID Using Model::create
One common way to insert data into the database and get the last inserted ID is by using the create
method on an Eloquent model. This method not only inserts the data but also automatically fetches the last inserted ID. You can easily access the ID as a property as: $user->id
. Consider the following example:
use App\Models\User;
$user = User::create([
'name' => 'Steve Rogers',
'email' => 'captain.america@marvel.com',
'password' => bcrypt('password123'),
]);
$lastInsertedId = $user->id;
Note that when passing an array of properties to the
create
function, make sure they are defined as fillable, otherwise the values won’t be written into the database. In our example this means we need to ensure the classUser
properly defines:protected $fillable = ['name', 'email', 'password'];
Method 2: Retrieving Insert ID Using new Model()
and save()
Another approach to insert data and retrieve the last inserted ID is by creating a new instance of the model, setting the attributes, and then calling the save
method. You can easily access the ID as a property with $user->id
. Let’s consider the following example:
use App\Models\User;
$user = new User();
$user->name = 'Natasha Romanoff';
$user->email = 'black.widow@marvel.com';
$user->password = bcrypt('password123');
$user->save();
$lastInsertedId = $user->id;
Method 3: Retrieving Insert ID Using DB Facade insertGetId()
When you need to insert data without using Eloquent models, you can utilize the insertGetId
method provided by the DB facade.
use Illuminate\Support\Facades\DB;
$lastInsertedId = DB::table('users')->insertGetId([
'name' => 'Bruce Banner',
'email' => 'hulk@marvel.com',
'password' => bcrypt('password123'),
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
Note that inserting records using this method will not fill your timestamp values automatically, even if they are defined in your Migration. For this reason we’ve included code to generate them manually using Carbon in the code above.
Method 4: Retrieving Insert ID Using Model::insertGetId
If you are inserting data directly through a model and want to retrieve the last inserted ID, you can use the insertGetId
method on the model itself.
use App\Models\User;
$lastInsertedId = User::insertGetId([
'name' => 'Clint Barton',
'email' => 'hawkeye@marvel.com',
'password' => 'password123',
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
Note that inserting records using this method will not fill your timestamp values automatically, even if they are defined in your Migration. For this reason we’ve included code to generate them manually using Carbon in the code above.
Method 5: Direct Access to PDO to access lastInsertId()
You can also directly access the PDO instance to retrieve the last inserted ID.
use Illuminate\Support\Facades\DB;
DB::table('users')->insert([
'name' => 'Peter Parker',
'email' => 'spiderman@marvel.com',
'password' => bcrypt('password123'),
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
$lastInsertedId = DB::getPdo()->lastInsertId();
Note that inserting records using this method will not fill your timestamp values automatically, even if they are defined in your Migration. For this reason, we’ve included code to generate them manually using Carbon in the code above.
Conclusion
By following the methods outlined in this blog post, you can easily obtain the last inserted ID using Eloquent models, the DB facade, or direct access to the PDO instance.
Choose the method that suits your needs. However, it’s worth noting that method 1 and method 2 are the most commonly used in Laravel applications. Happy coding!
References
- Laravel Eloquent (Laravel Documentation)
- Laravel Database (Laravel Documentation)