Insert bulk records of data into database using Laravel query builder

  

Code to insert bulk records of data into database using Laravel/Lumen query builder

Let's say below is your table structure. 

The table name is the person with the below columns:


id int(11),
firstName varchar(100),
lastName varchar(100),
age int(3),
address varchar(200),
created timestamp

If you want to write a query to insert 50 records at a time instead of inserting 50 times in a loop then you can use the query builder style to write like below:


<?php

$data = array();

foreach ($records as $row) {

    // Create an array of data where one array is a row so that
    // multiple rows can be inserted at a time
    $data[] = [
        'firstName' => $row['firstName'],
        'lastName' => $row['lastName'],
        'age' => $row['age'],
        'address' => $row['address'],
    ];
}

DB::table('person')->insert($data);


Let me know if you have any questions :)


Thanks!

No comments:

Post a Comment