This content originally appeared on DEV Community and was authored by Morcos Gad
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.
This content originally appeared on DEV Community and was authored by Morcos Gad
Morcos Gad | Sciencx (2022-02-11T18:46:24+00:00) Four Ways Get Last ID of an Inserted Model – Laravel. Retrieved from https://www.scien.cx/2022/02/11/four-ways-get-last-id-of-an-inserted-model-laravel/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.