DB Transactions query looping alternative

Posted 11 months ago by ochirach

Hi,

Version: 5.4

Method: Query Builder after storing the .csv as an array $headers for columns, $data_rows for the data

Aim: I want to add users phone numbers via a .csv file to my database.

Problem: Is there a better method other than looping through each row?

The entries can be up to 5000 users which results in 5000 insert queries. To ensure all are added at a go I have setup the insert process to run within a transaction.

Below is a simplified version of the code:

DB::transaction(function() use ($request, $headers, $data_rows) {

foreach ($data_rows as $row) { // loop through each row

    DB::table('user_phone_numbers')->insert(
                    [
                        'user_id' => $row[$user_index_from_csv_here], 
                        'number' => $row[$user_number_from_csv_here], 
                        'created_at' => date("Y-m-d H:i:s"), // now
                        'updated_at' => date("Y-m-d H:i:s"), // now
                    ]
                );

} // end foreach

});

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.