Just to be sure, when you say insert, you just mean 1 record right?
Laravel 8 Get all Last ID of an Inserted
how to get Laravel 8 Get all Last ID of an Inserted
@Sinnbeck no all recent inserted record ids
@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.
@Sinnbeck suppose inserted all product by foreach after all product are inserted than how I get all recent inserted all products ids.
$product = DB::table('users')->insert( [ 'name' => 'Acer Aspire 5 Slim Laptop' ] ); $productId = DB::getPdo()->lastInsertId();.
dd($productId);
@ga46 You need to get them right after inserting
$ids = [];
foreach ($inserts as $insert) {
$ids[] = DB::table('users')->insertGetId($insert);
}
dd($ids);
@Sinnbeck any other way to get all the latest insert products ids?
@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
This is a limitation with pdo and mysql, not laravel. So maybe consider if you can handle it in batches
$product = Product::create(['name' => 'Acer Aspire 5 Slim Laptop']);
$productId = $product->id();
dd($productId); // will spit out product id
@Muhammad_Shoaib_Ali this way to get only one product inserted id.
any other way to get all the latest insert products ids?
Why?
@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
@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?
@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?
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.
@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.