DEV Community

Morcos Gad
Morcos Gad

Posted on

Four Ways Get Last ID of an Inserted Model - Laravel

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.

  1. Using Eloquent Save Method
$product = new Product();
$product->name = "product name";
$product->save();

$productId = $product->id();
dd($productId); // will spit out product id
Enter fullscreen mode Exit fullscreen mode
  1. Using Elogquent Create Method
$product = Product::create(['name' => 'product name']);

$productId = $product->id();
dd($productId); // will spit out product id
Enter fullscreen mode Exit fullscreen mode
  1. Using DB Facade (insertGetId())
$productId = DB::table('products')->insertGetId(
    [ 'name' => 'product name' ]
);

dd($productId); // will spit out product id
Enter fullscreen mode Exit fullscreen mode
  1. Using getPDO() Method (lastInsertId())
$product = DB::table('users')->insert(
    [ 'name' => 'product name' ]
); 
$productId = DB::getPdo()->lastInsertId();.

dd($productId); // will spit out product id
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed.

Top comments (0)