Bulk Insertion in Laravel using Eloquent ORM
Performing bulk database insertions in Laravel using Eloquent ORM is a straightforward process. Consider the following steps:
1. Define Your Data Array:
To begin, define an array containing the data you wish to insert. Each array element should represent a single row. For instance:
$data = [ ['name' => 'Coder 1', 'rep' => '4096'], ['name' => 'Coder 2', 'rep' => '2048'], //... ];
2. Use Eloquent::insert():
Once the data array is defined, you can utilize Eloquent's insert() method to perform the bulk insertion. The syntax is straightforward:
Coder::insert($data);
Example:
To insert the data from the provided XML document, you could modify your code as follows:
foreach ($oXML->results->item->item as $oEntry) { $data[] = [ 'first_name' => $oEntry->firstname, 'last_name' => $oEntry->lastname, 'date_added' => date("Y-m-d H:i:s"), ]; } Item::insert($data);
Additional Considerations:
The above is the detailed content of How to Perform Bulk Inserts in Laravel Using Eloquent?. For more information, please follow other related articles on the PHP Chinese website!