When working with databases, one common task is to retrieve the ID of the last record you inserted. This is especially useful when you want to use that ID immediately after saving a new record, such as linking it to another table or displaying it to the user. Laravel’s Eloquent ORM makes this task incredibly simple and intuitive. This article will guide you step-by-step on how to get the last inserted ID using Laravel Eloquent, explained in easy language for beginners.
What is Laravel Eloquent?
Laravel Eloquent is an Object-Relational Mapping (ORM) tool that helps you interact with your database using PHP objects instead of writing raw SQL queries. It allows you to work with your database tables as if they were PHP classes, making database operations more readable and easier to manage.
When you create or save a new record using Eloquent, Laravel automatically handles the database insert operation behind the scenes. But how do you get the ID of that newly created record? Let’s find out.
Why Do You Need the Last Inserted ID?
Imagine you have two tables: users
and profiles
. After creating a new user, you want to create a profile linked to that user. To do this, you need the user’s ID immediately after inserting the user record. Getting the last inserted ID is crucial for:
-
Creating related records in other tables.
-
Displaying confirmation messages with the new record’s ID.
-
Performing further operations that depend on the newly created record.
Using Eloquent’s save()
Method and Getting the ID
The easiest way to get the last inserted ID is by using Eloquent’s save()
method on a model instance. When you save a new model, Laravel automatically fills the model’s id
property with the newly generated primary key.
Here’s how you can do it:
$user = new User;
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->password = bcrypt('password123');
$user->save();
$lastInsertedId = $user->id;
echo "The last inserted user ID is: " . $lastInsertedId;
In this example:
-
A new
User
object is created. -
The user’s details are assigned.
-
The
save()
method inserts the record into the database. -
After saving,
$user->id
holds the ID of the newly inserted user.
This method is straightforward and recommended for beginners.
Using Eloquent’s create()
Method and Getting the ID
Laravel also provides the create()
method, which combines creating and saving a new record in one step. To use create()
, make sure your model has the $fillable
property set to allow mass assignment.
Example:
// In User model
protected $fillable = ['name', 'email', 'password'];
// In controller or elsewhere
$user = User::create([
'name' => 'Jane Smith',
'email' => '[email protected]',
'password' => bcrypt('securepass'),
]);
$lastInsertedId = $user->id;
echo "The last inserted user ID is: " . $lastInsertedId;
Here, User::create()
inserts the record and returns the model instance with the ID property already set.
Using the Query Builder and Getting the Last Inserted ID
If you prefer using Laravel’s Query Builder instead of Eloquent, you can still get the last inserted ID easily.
Example:
$lastInsertedId = DB::table('users')->insertGetId([
'name' => 'Alice Johnson',
'email' => '[email protected]',
'password' => bcrypt('mypassword'),
]);
echo "The last inserted user ID is: " . $lastInsertedId;
The insertGetId()
method inserts the record and returns the ID of the new row immediately.
Important Tips to Remember
-
Make sure your database table has an auto-incrementing primary key (usually
id
) for Laravel to retrieve the last inserted ID. -
When using
create()
, always define the$fillable
or$guarded
properties in your model to avoid mass assignment errors. -
The ID is only available after the record is successfully saved to the database.
-
Using Eloquent models is generally preferred for cleaner and more maintainable code, but Query Builder is useful for simpler or more complex queries.
Conclusion
Getting the last inserted ID in Laravel is a breeze thanks to Eloquent’s intuitive methods. Whether you use the save()
method on a model instance, the create()
method for mass assignment, or the Query Builder’s insertGetId()
, Laravel provides clear and easy ways to access the ID of newly created records. This functionality is essential for building relational data and creating dynamic, responsive applications. With these simple techniques, even beginners can confidently handle database inserts and immediately use the newly generated IDs in their Laravel projects.