DB Transactions query looping alternative

Posted 6 months ago by ochirach


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

                        '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.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.