Laravel 11 Get ID of Inserted Model

Laravel 11 Get ID of Inserted Model

Laravel 11 Get ID of Inserted Model

While developing a web app, you might need to get the ID of the 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 an entry in db

– We create a new entry in the DB and right after we grab 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 similar to the previous method. We use save() method to get ID in this method.

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

$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 insertGetId() method which inserts data in the table and also returns the id of the row.

$itemsID = DB::table('items')->insertGetId(
    [ 'name' => 'Dell XPs' ]
);

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

4 - getPDO()

To get the last inserted ID, we can also use the PDO object. At first, insert the data in the table and then call the lastinsertedId() method on the 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 the ID of inserted data. I hope this helps you in your Laravel development journey.

All Comments