Laravel 8 Get Last ID of an Inserted Model
In this post, I want to share a quick tip about how to get the last inserted ID in Laravel. While working on your Laravel application, you often need to get the recently added model ID to assign it to some other model or processing data. You can achieve this in different ways and also depends you are using the DB facade of Laravel or using a model class.
So without any delay, let’s see how we can get the last inserted ID of a model/table in Laravel.
1. Using Eloquent Save Method
One of the easiest and most efficient ways to grab the last inserted ID for a model is to use the
save() method when you create/update an eloquent model.
$product = new Product(); $product->name = "Acer Aspire 5 Slim Laptop"; $product->save(); $productId = $product->id(); dd($productId); // will spit out product id
In the above example, we created a new product using the Product model, and right after saving the model we assigned the id of the last saved product to
2. Using Elogquent Create Method
This method is the same as the previous one, except we create the model entry using
create() method. In this method, we will create a new product using the create method, and right after the creation, we can grab the id of the model.
$product = Product::create(['name' => 'Acer Aspire 5 Slim Laptop']); $productId = $product->id(); dd($productId); // will spit out product id
3. Using DB Facade
You can also create the model/table entry using the DB facade and get the ID right at the same time. For this purpose, we can call the insertGetId() method to insert and return the id of the table row.
$productId = DB::table('products')->insertGetId( [ 'name' => 'Acer Aspire 5 Slim Laptop' ] ); dd($productId); // will spit out product id
4. Using getPDO() Method
You can also use the PDO Object to get the last inserted id of a table in Laravel. Firstly you will have to insert the record and right after that, you can call the lastInsertId() method on the PDO object.
$product = DB::table('users')->insert( [ 'name' => 'Acer Aspire 5 Slim Laptop' ] ); $productId = DB::getPdo()->lastInsertId();. dd($productId); // will spit out product id
That’s all for now. I hope this small tip will help you but I guess most of you will know these or some of these methods already if you are in Laravel development for some time. If you have any questions or comments please let us know in the comments box below.