Get ID of inserted Model

While developing a web app, you might need to get the id of last inserted data to assign to another model. There are various ways to achieve it depending on whether you are using model class or DB facade.

1. Eloquent Create Method

In this technique, we use create() method to add entry in db. We create new entry in the db and right after we grab of the model. Here is a snippet of this process.

$user = User::create(['name' => 'John Doe']);
$user_id = $user->id();

Above, we created a user and stored it in a variable. Using that variable we assign the id to another variable. Hence, we get the id.

2. Eloquent Save Method

This process is very much similar to the previous method. We use save() method to get id in this method.

$user = new User();
$user->name = 'John Doe';

$user_id = $user->id();

3. DB Facade

By using DB Facade, we can get ID at the time of insertion of data. For this we can call inserGetId() method which inserts data in the table and also returns id of the row.

$itemsID = DB::table('items')->insertGetId(
    [ 'name' => 'MSI GP63' ]

dd($itemID); // will return item id

4. getPDO()

To get last inserted id, we can also use PDO object. At first, insert the data in the table and then call lastinsertedId() method on PDO object.

$item= DB::table('items')->insert(
    [ 'name' => 'MSI GP63' ]
$itemId = DB::getPdo()->lastInsertId();.

dd($itemId); // will return item id

These are some of the methods that you can use to get id of inserted data. I hope this helps you in your laravel development journey.

Leave a Comment