I found this great resource https://www.larashout.com/laravel-8-get-last-id-of-an-inserted-model which contains 4 methods Get Last ID of an Inserted Model It's great to share this as from projects I needed to get an ID I will show briefly, but visit the source to go deeper.
- Using Eloquent Save Method
$product = new Product();
$product->name = "product name";
$product->save();
$productId = $product->id();
dd($productId); // will spit out product id
- Using Elogquent Create Method
$product = Product::create(['name' => 'product name']);
$productId = $product->id();
dd($productId); // will spit out product id
- Using DB Facade (insertGetId())
$productId = DB::table('products')->insertGetId(
[ 'name' => 'product name' ]
);
dd($productId); // will spit out product id
- Using getPDO() Method (lastInsertId())
$product = DB::table('users')->insert(
[ 'name' => 'product name' ]
);
$productId = DB::getPdo()->lastInsertId();.
dd($productId); // will spit out product id
I hope you enjoyed.
Top comments (0)