ga46's avatar
Level 1

Laravel 8 Get all Last ID of an Inserted

how to get Laravel 8 Get all Last ID of an Inserted

0 likes
17 replies
Sinnbeck's avatar

@ga46 Then you need to insert them one by one. PDO does not have a way of getting ids from multiple inserts in one query.

ga46's avatar
Level 1

@Sinnbeck suppose inserted all product by foreach after all product are inserted than how I get all recent inserted all products ids.

Muhammad_Shoaib_Ali's avatar

@ga46

$product = DB::table('users')->insert( [ 'name' => 'Acer Aspire 5 Slim Laptop' ] ); $productId = DB::getPdo()->lastInsertId();.

dd($productId);

Sinnbeck's avatar

@ga46 You need to get them right after inserting

$ids = [];
foreach ($inserts as $insert) {
    $ids[] = DB::table('users')->insertGetId($insert);
}
dd($ids);
ga46's avatar
Level 1

@Sinnbeck any other way to get all the latest insert products ids?

Sinnbeck's avatar

@ga46 Yeah I can see @muhammad_shoaib_ali as already posted two? But it is still the same under the hood. They are just different ways to call the same method in PDO

Sinnbeck's avatar

This is a limitation with pdo and mysql, not laravel. So maybe consider if you can handle it in batches

Muhammad_Shoaib_Ali's avatar

$product = Product::create(['name' => 'Acer Aspire 5 Slim Laptop']);

$productId = $product->id();

dd($productId); // will spit out product id

Snapey's avatar

any other way to get all the latest insert products ids?

Why?

ga46's avatar
Level 1

@Snapey $ids = []

when we insert 10k data that mean this array has 10k new id. then again we ned to query get the product image or other column for update. so its a big query to get data info

Sinnbeck's avatar

@ga46 Why would you need to get the ids of 10k records? Thats a lot for php to hold in memory. Where does 10K records come from?

Snapey's avatar

@ga46 So let me get this straight

You want to insert up to 10K rows into the database then iterate over each of them to add an image to each?

dev-mo's avatar

It is possible to insert multiple rows into a database table with a single query using PDO, but you won’t be able to retrieve the IDs of all inserted rows with a single query.

If you need to insert multiple rows and retrieve the IDs of all inserted rows, you would need to perform multiple inserts, one for each row, and retrieve the ID for each inserted row.

Snapey's avatar

@dev-mo thats what we said. Not sure why you needed to bump a 7 month other thread?

Please or to participate in this conversation.