I stored an array in the database using the Laravel insert Eloquent method as below:
$newTags = [
[
'name' => 'tag1'
],
[
'name' => 'tag2'
],
];
if (sizeof($newTags) > 0) {
Tag::insert($newTags);
}
After that, is there a way to get the id of the saved items?
Advertisement
Answer
For bulk insertion there’s no built in method to get inserted IDs. You can use foreach loop to insert one by one and get the IDs using insertGetId and put them into an array.
$insertedIDs = [];
if (count($newTags) > 0) {
foreach ($newTags as $newTag) {
$insertedIDs[] = Tag::insertGetId($newTag);
}
}